Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

if statement - Evaluation of the if condition in c as true or false

int n,i;

scanf("%d",&n);

if(n==0)
printf("a");

else if (!(n>=1))
printf("b");

When I give the input as m, the condition (n==0) is evaluating to be true. When the condition is a valid expression and non-zero, then it's true. When I am replacing n by i and providing the same input, the condition n==0 is getting evaluated as false. Why is this happening?. Why is it evaluating to be true even when there's 0 in n==0 ?

question from:https://stackoverflow.com/questions/65642077/evaluation-of-the-if-condition-in-c-as-true-or-false

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

1 Answer

0 votes
by (71.8m points)

The definition of scanf() says nothing about what it will do to the value of arguments that cannot be assigned, but invariably in practice, it leaves them untouched.

In this case both n and i are unitialised and may contain any value - in your case n happened to contain zero at the moment you tried it, but that is not a given - it is undefined. The C runtime is not required to initialise variables with auto storage class (local, non-static) to zero.

int n = 0; 
int i = 0;

Note also that sscanf() returns the number of format specifiers that result in a successful assignment, so you can for example:

while( scanf("%d",&n) == 0 )
{
    // wait until valid input
}

This is strictly safer than relying only initialisation of a "default" value because scanf() strictly makes no guarantees that it will not modify an argument in any case - it would only be an unusual implementation that did so. Also in practice you would normally want to handle erroneous input one way or another rather then simply ignore it and use a default. A safe and unambiguous way of providing a default if required is:

if( scanf("%d",&n) == 0 )
{
    n = 0 ;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...