Let us consider the following program.
#include <stdio.h>
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
int square_of(const int value)
{
// int expr = value * value;
// return expr;
}
int main(void)
{
int test_val = 15;
int res = square_of(test_val);
fprintf(stdout, "The square of %d is %d.\n", test_val, res);
return EXIT_SUCCESS;
}
The output without using the optimization flag is as follows:
The square of 15 is 15.
However, when the optimization is used, for example, -O1
, -O2
, -O3
, the issue is fixed, and the output is as expected:
The square of 15 is 0.
I am unable to understand why the program is behaving this way. Is it an undefined behavior or something else?
Note: I am aware of the control reaching non-void function warning:
main.c: In function ‘square_of’:
main.c:10:1: warning: control reaches end of non-void function [-Wreturn-type]
10 | }
| ^
The function square_of
has no return
statement while it is declared to return an int
value: using the return value is Undefined Behaviour. On most common compilers, you will get an unpredictable value, but standard does not even prevent trap values.
You get either the original value (without optimizations) or a 0 value only by chance or by accident and should not rely on it.
Warning are not to be ignored. As a compiler is allowed to assume that the code should not contain UB, it is free to optimize out any code where UB can be detected...