AgainPsychoX
AgainPsychoX

Reputation: 1821

How does C compiler `-O0` make code go so crazy?

Please take a look at: https://godbolt.org/z/WGBP8D

Code:

    size_t n;
    scanf("%d", &n);
    fprintf(stderr, "(1 <= %d) == %d\n", n, 1 <= n);
    fprintf(stderr, "(%d <= 1000) == %d\n", n, n <= 1000);
    fprintf(stderr, "%d\n", 2 <= 1000);
    ASSERT(1 <= n && n <= 1000);

Input is set to be:

2
1
2

Output:

(1 <= 2) == 1
(2 <= 1000) == 0
1
Assertion failed: 1 <= n && n <= 1000

Commenting out further part of code changes behavior of the snippet above. How is that?

Funny thing is, any optimization enabled (-O1) works nicely, but no optimization (-O0 or not specified) makes it... Well, I don't even know how to understand it.

Upvotes: 0

Views: 168

Answers (1)

Simon Willcocks
Simon Willcocks

Reputation: 328

scanf is affecting just the bottom 32 bits of the 64-bit n. printf is displaying just that bottom 32 bits, as well, but with some optimisation, there's something in the upper 32-bits, making n bigger than 1000, hence this line of output:

(2 <= 1000) == 0

Using -Wall will probably warn you of the problem.

Upvotes: 4

Related Questions