user3994531
user3994531

Reputation:

unexpected result when i entered character instead of integer value in scanf

here is my code where i am facing a problem regarding datatypes in c

#include<stdio.h>
int main()
{  
int a,b;
scanf("%d",&b);
printf("%d",b);
}

When In Entered Any Character Instead Of Integer values It always Prints 32. Am Not Getting Why Its printing 32.

Upvotes: 1

Views: 131

Answers (2)

godel9
godel9

Reputation: 7390

If you try the following modification, you might get some insight:

#include<stdio.h>

int main()
{
    int a, b;
    a = scanf("%d",&b);
    printf("%d %d",a,b);
}

When you type anything other than an integer, scanf returns 0, meaning that none of the items in the argument list was successfully filled. That means b has whatever value it had before the call to scanf. Since b is never initialized, this value is undefined.

P.S. Your main function should return type int, not void.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

The value that gets printed is completely arbitrary. It is a result of undefined behavior, because b remains unassigned.

You need to check that the user has entered a value before proceeding. scanf returns the number of items that it has processed, so your code should not use the value unless scanf has returned 1, indicating that one item has been read successfully:

int b;
for (;;) { // Repeat forever
    int numRead = scanf("%d",&b);
    if (numRead == 1) {
        // We've got our number; end the loop:
        break;
    }
    printf("You did not enter a number\n");
    // Consume the data that cannot be interpreted as a number.
    // Asterisk means "discard the value":
    scanf("%*s");
}
printf("b=%d\n", b);

Demo.

Upvotes: 3

Related Questions