Reputation: 5730
This is my basic C test program.
After I built it, I just entered negative number like -1
, -2
, etc. in console.
But the result is "oh", not "another number".
I don't know why this happens, because negative numbers should make the 'if' statement true.
int main(int argc, char* argv[]){
long int num;
scanf("%d", &num);
if(num ==1 || num < 0){
printf("another number\n");
}else{
printf("oh\n");
}
}
Upvotes: 0
Views: 120
Reputation: 12402
/tmp$ gcc -Wall foo.c
foo.c: In function ‘main’:
foo.c:4:5: warning: implicit declaration of function ‘scanf’ [-Wimplicit-function-declaration]
foo.c:4:5: warning: incompatible implicit declaration of built-in function ‘scanf’ [enabled by default]
foo.c:4:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘long int *’ [-Wformat]
foo.c:7:9: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
foo.c:7:9: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
foo.c:9:9: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
foo.c:11:1: warning: control reaches end of non-void function [-Wreturn-type]
fix the causes of those warnings and all the bugs will go away.
Upvotes: 1
Reputation: 283624
When you use the %d
format string with scanf, the corresponding argument will be treated as int*
. But you have passed a long int*
. The value scanf
stores will not be the same size as what your if
statement reads.
Formally, you get undefined behavior. In practice, on most platforms scanf
will write only part of the variable, and the rest will be left with an arbitrary value, with the usual bad effects on future use.
Upvotes: 2
Reputation: 361565
Use %ld
for long
variables, %d
for int
s. Change your code to one of these:
int num;
scanf("%d", &num);
or
long int num;
scanf("%ld", &num);
Upvotes: 2