0

I am new to C and wondering how to properly build primitive functions in order to handle errors. Take for example the following function:

bool
testIfEqual(int a, int b) {
  return a == b;
}

Wondering if there are certain classes of errors that the compiler wont detect that this function should account for if it were to be robust.

Things like buffer overflows, max integer size, perhaps something that can sneak between the cracks of the type safety somehow.

Basically wondering if there are certain classes of errors for the primitive operators that should be accounted for in a robust application:

  • ==
  • +
  • -
  • / (divide by zero)
  • *
  • &&
  • ||
  • &
  • |
  • >>
  • <<
  • >
  • <
  • >=
  • <=
  • !=
  • !

Not looking for a complete list of stuff, but just general guidelines on best practices for covering standard errors these operators may be involved in.

I would typically write an application without ever thinking of errors that these things could be involved in, but if you have a function like above, wondering what errors it might create in C so I can cover them. Making sure I'm not missing anything.

2

Your testIfEqual is as robust as it can be.

AFAIK the only errors you have to care for by arithmetic expressions in C (which are not covered by a standard compiler) are

  • division by zero (as you already mentioned)

  • arithmetic overflow / underflow

  • left shift E1 << E2 where E1 < 0 (thanks to Philip Kendall, link from his comment)

  • errors caused by restricted precision of floating point numbers

These are the cases where you may need to add some extra error handling code to the arithmetic expressions to deal with them correctly.

Some debatable cases, which I personally do not really see as an "error", but as "standard behaviour" you simply have to know:

  • division of two integers automatically truncates to the next smaller integer, even if the exact result is a non-integer fraction

  • as mentioned by Robert Harvey: unexpected behaviour / (non-)side effects because of short-circuiting

That should be the complete list (but if I missed something, please leave a comment, I will update the list happily).

Warning: the above list is for standard arithmetic, not pointer arithmetic, of course! Pointer expressions and arithmetic have tons of additional pitfalls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.