Why does this program stop working if I leave out the reference to userNumber in the scanf function?
#include <stdio.h>
int main()
{
int userNumber;
printf("Enter a number: ");
scanf("%d", &userNumber);
while (userNumber != 10)
{
printf("nWrong number. Try againn");
printf("nEnter a number: ");
scanf("%d", &userNumber);
}
return 0;
}
5
scanf(“%d”) requires to pass a pointer as its second argument, thus you really need to write:
int userNumber;
scanf("%d", &userNumber);
If you take out the reference, then input is not read correctly, and userNumber
is actually left uninitialized, which causes Undefined Behavior, which probably explains the behavior you witness.
You should have seen a warning, if you had removed the reference from the first scanf:
Georgioss-MacBook-Pro:~ gsamaras$ gcc main.c
main.c:8:17: warning: format specifies type 'int *' but the argument has type
'int' [-Wformat]
scanf("%d", userNumber);
~~ ^~~~~~~~~~
1 warning generated.
7