Clang overflow overflow

Using -Wall -pedantic

#include <limits.h> #include <stdio.h> int main(void) { enum x { a, max = INT_MAX, out_1 }; enum y { b, out_2 = INT_MAX + 1 }; printf("%d %d\n", out_1, out_2); return 0; } 

clang returns

 demo.c:9:3: warning: overflow in enumeration value out_1 ^ 

As you can see, the compiler does not warn about out_2 overflow, its value is unknown at compile time?

+5
source share
2 answers

In the first case, the compiler itself tries to select an integer that causes an overflow, and therefore warns you. It probably produces INT_MIN . The standard allows any value in signed int be an enumeration constant (see bottom).

The second expression (INT_MAX + 1) evaluated before it is assigned the value out_2 . Overflow in the expression here gives a result that is allowed, but this behavior is undefined. Then the actual result is stored in the enumeration, so the first error is not created.

clang (3.2) will also not warn about this, which is virtually identical:

 int a = INT_MAX + 1; 

In this regard, clang does not behave according to the C standard, as it is undefined.

The result from gcc in comparison makes the difference very clear:

 In function 'main': 9:9: error: overflow in enumeration values 13:25: warning: integer overflow in expression [-Woverflow] 

Intel compiler ignores enumeration overflow, but warns about integer overflow:

 enum.c(13): warning #61: integer operation result is out of range out_2 = INT_MAX + 1 ^ 

<h / "> For reference, from the C99 standard 6.7.7.2.2," The expression defining the value of an enumeration constant must be an integer constant expression that has a value represented as int ; .3, "Identifiers in the list enumerator are declared as constants with type int and may appear wherever permitted. " That is, the enumeration constant can be any int value and is of type int . The resulting type of a particular enumeration variable can be char , int or unsigned int if it allows all possible constants in the enumeration. Thus, the enums in this example are undefined, since they both require integer overflows. clearly illegal.

+1
source

ISO C defines integers as enum values.

If your compiler allows this (both GCC and Clang), then INT_MIN is a great value.

If the compiler has not resolved the specified index, an error is required.

The reason the explicitly requested INT_MIN is fine, but the automatically incremented value from the predecessor INT_MAX, causes a warning that the standard requires +1 Behavior.

0
source

Source: https://habr.com/ru/post/987784/


All Articles