Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined behaviour by declaration [duplicate]

Tags:

c

standards

Let's talk about enum in C.

According to the C standard (ISO/IEC 9899:201x), the following statements hold true:

  • § 6.7.2.2:

The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.

The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted.127) An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. [...]

  • § 6.5:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

Analogously to can an enum hold unsigned integers greater than INT_MAX?, should I infer that the following is undefined?

#include <limits.h>
enum {
   x = INT_MAX,
   y,
};
like image 689
Dacav Avatar asked Dec 30 '19 17:12

Dacav


1 Answers

The standard also states that:

Each subsequent enumerator with no= defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant.

A good-enough C compiler should give you error: overflow in enumeration values, so you won't even pass the compiling phase.

If you do this instead, you might get rid of that warning:

enum {
   x = INT_MAX,
   y = INT_MAX + 1,
};

Anyway, even if you get no problem with compiling: yes, it's undefined behavior because you got signed integer overflow.

like image 121
Trevor Avatar answered Oct 13 '22 00:10

Trevor