Reputation: 325
I am taking C programming course. I did not understand these codes.
#include <stdio.h>
int main()
{
int c;
int ival;
printf("type : ");
c = getchar();
scanf("%d", &ival);
printf("c = %d\n", c); //65
printf("ival = %d\n", ival); //127
return 0;
}
For example whenever I type Abc, I am getting c = 65; ival = 1. why ival is 1?
Upvotes: 0
Views: 569
Reputation: 47513
ival
is never initialized, so it can have any value. The reason is that, c
is receiving 'A'
(through getchar()
) and then scanf
fails to read a number (since the next character in the input, 'b'
, is not a decimal number), so it never touches ival
.
You can check the return value of scanf
to see if it fails or succeeds:
if (scanf("%d", &ival) != 1)
printf("you need to enter a number\n");
else
printf("entered: %d\n", ival);
Note that scanf
returns the number of items it successfully read and assigned. For example scanf("%d %f %c", ...)
would return 3 if all three items were correctly read.1
1Note that assigned means that ignored input (such as those with the assignment-suppresion modifier (*
)) doesn't count towards the return value of scanf
(C11, 7.21.6.2.10,16). Furthermore, %n
doesn't affect the return value of scanf
(C11, 7.21.6.2.12).
Upvotes: 5
Reputation: 21213
With Abc
, getchar()
will read A
, thus, c
will hold the character code for A
, which happens to be 65 on your machine (this is the ascii code for A
).
For ival
, you can get anything: since %d
on scanf()
expects to read an integer, and you didn't provide one, scanf()
returned prematurely, leaving bc
in the input buffer, so the value you read from ival
when you call printf()
is undefined: it can print anything.
Upvotes: 2
Reputation: 106012
The reason is that your program invokes undefined behavior.A
is read by getchar
while bc
is left unread by scanf
because %d
expects to read an integer and hence on encountering the character it stop reading immediately and leave ival
uninitialized.
Upvotes: 0