I've just started learning C and would need some help here:
#include <stdio.h>
int main (){
int x, y;
scanf("%d/%d", &x, &y);
printf("%d,%d", x, y);
return 0
}
If I run the above code and only input 1 integer ('12'), it will print ('12,16'). Can someone explain how did the '16' come about?
CodePudding user response:
If input stream contains just one number then the second value is not read. You would know that if you checked the return value:
int numbersread = scanf("%d/%d", &x, &y);
Then the y
variable is uninitialized and it contains some garbage value. In your case it's 16.
CodePudding user response:
The scanf
function will fail to find a /
character in the input and will stop reading there. It will not assign any value to y
, which will remain uninitialized and will thus contain an indeterminate value. In your case, this was 16, but it could have been any other value, and this value could change when executing the program multiple times. The value is typically something that was used by the same process and was left in that memory location, and is now being interpreted as an int
.
If the address of y
was not taken, printing its value would have been undefined behavior (C11 6.3.2.1-2):
If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.
However, since the address of y
was taken (&y
), its value is simply indeterminate. The lvalue y
"is converted to the value stored in the designated object (and is no longer an lvalue); this is called lvalue conversion".
It is a good practice to always check the return value of scanf
- which contains the "number of receiving arguments successfully assigned" - which allows you to handle the case of incorrect input.
Acknowledgements: Credits to Andreas Wenzel and Eric Postpischil for the correction on the origin of the indeterminate value.