Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

c - Why, on entering a wrong type of value as input, the variable "b" is always assigned to 1?

In this simple code,

#include <stdio.h>
int main(void)
{
     int a, b;
     scanf("%d %d",&a,&b);
     printf("
The value of a is : %d",a);
     printf("
The value of b is : %d",b);
}

When I enter a wrong type of value as input, the variable b is always getting assigned to 1. I have tried to add another variable "c" and printed its value at the end of the code, but still the variable "b" is always assigned to 1. Why?

The output:-

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If value of a scanf() argument after scanf() returns is undefined if the conversion was unsuccessful, but the most likely behaviour is that it remains unchanged. In this case b is uninitialised so could have any value regardless of the behaviour of scanf() .

Consider:

#include <stdio.h>
int main(void)
{
    int a = -1, b = -1;
    scanf("%d %d",&a,&b);
    printf("
The value of a is : %d",a);
    printf("
The value of b is : %d",b);

    return 0 ;
}

I would expect in this case both a and b to have either the entered value or -1 if the conversion fails - even though that is not actually required.

scanf() returns the number of arguments converted and assigned. Consider:

#include <stdio.h>
int main(void)
{
    int a = 0, b = 0;
    int convert = scanf("%d %d",&a,&b) ;
    if( convert > 0 )
    {
        printf("
The value of a is : %d",a);

        if( convert > 1 )
        {
            printf("
The value of b is : %d",b);
        }
        else
        {
            printf("
The value of b is undefined" );
        }
    }
    else
    {
        printf("
The value of a is undefined" );
    }

    return 0 ;
}

For your test input 54test hello it outputs:

45test hello


The value of a is : 45
The value of b is undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...