4
#include <stdio.h>

int main(void)
{
    int i, j, k;
    scanf("%d%d%d", &i, &j, &k);
    printf("%d %d %d", i, j, k);
    return 0;
}

If we input 1,2,3, what will happen? And why?

According to https://stackoverflow.com/a/18297691/2646069 , if scanf() reads an unexpected string, it will return early thus not modifying any value after the last successful value.

I tried clang (LLVM 6.1.0), on -O0, the explanation above is correct, but on -O2, the second variable is always a random number but not the same as before scanf(), and the third variable is always 0.

Community
  • 1
  • 1
Jamesits
  • 612
  • 7
  • 18

2 Answers2

5

According to the manual, scanfs return value tells you whether it's safe to use those arguments or not.

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned

If you were to input 1,2,3 then scanf would return 1, indicating that the first argument is safe to use and that a match failure occured at the first , because it doesn't match the input expected according to the format string.

If you were to make use of j or k following this, then your code would be making use of an indeterminite value, which is undefined behaviour, obviously a source of erratic behaviour to be avoided... It's very important that you check the return value of scanf, as the link you used also encourages.

autistic
  • 1
  • 3
  • 35
  • 80
1

The explanation given there is correct. scanf will stop and return when it will find , in input. Therefore j and k will be uninitialized. Uninitialized variables have indeterminate values and this will invoke undefined behavior if it is a trap representation.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • `j` and `k` would be indeterminite. Uninitialised variables don't invoke undefined behaviour, though they are indeterminite. Using indeterminite values invokes undefined behaviour. – autistic Apr 10 '15 at 01:28
  • @undefinedbehaviour; Yes. Ultimately they will invoke UB. – haccks Apr 10 '15 at 01:29