Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does INT_MIN % -1 produce undefined behavior?

Tags:

gcc generates floating code that raises SIGFPE for the following code:

#include <limits.h> int x = -1; int main() {     return INT_MIN % x; } 

However I can find no statement in the standard that this code invokes undefined or implementation-defined behavior. As far as I can tell, it's required to return 0. Is this a bug in gcc or am I missing some special exception the standard makes?

like image 955
R.. GitHub STOP HELPING ICE Avatar asked May 08 '11 01:05

R.. GitHub STOP HELPING ICE


People also ask

What causes undefined Behaviour in C?

So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.

What causes undefined behavior C++?

In C/C++ bitwise shifting a value by a number of bits which is either a negative number or is greater than or equal to the total number of bits in this value results in undefined behavior.

What is undefined behavior in programming?

In computer programming, undefined behaviour is defined as 'the result of compiling computer code which is not prescribed by the specs of the programming language in which it is written'. This article will help you understand this behaviour with the help of a few case studies.

What type of behavior C is undefined?

The C FAQ defines “undefined behavior” like this: Anything at all can happen; the Standard imposes no requirements. The program may fail to compile, or it may execute incorrectly (either crashing or silently generating incorrect results), or it may fortuitously do exactly what the programmer intended.


1 Answers

You are probably right that this can be considered as a bug in the actual standard. The current draft addresses this problem:

If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.

like image 188
Jens Gustedt Avatar answered Oct 30 '22 00:10

Jens Gustedt