Greetings everyone,

I am just starting out with C and I am stuck with a question in my book. It says the following:

x=1;  
y=1;
if(n>0)
      x=x+1;
      y=y-1;
      printf("%d%d"x,y);

What will be the values of x and y if n assumes a value of a) 1 and b) 0.

Now when I run the program assuming n has a value of 1 then the output is x=2 and y=0 and when n is 0 then x=1 and y=0 (This is strange for me). Now when I run the same program using if else statement then I get X=2 Y=0 (Considering N is 1 here as well) and X=1 and Y=1 when N is 0 (This is what I agree with as well).

I am certain that either I do not have a clear concept here or maybe I am missing out on something. Any help is appreciated and Thanks in advance. Cheers !!

VikashS_
Deleted Member

The way the code is currently written, only the first expression after if (n > 0) will be evaluated, provided that n is indeed greater than zero.
Rewriting the code using braces it would be equivalent to:

x=1;  
y=1;

if (n > 0)
{
    x = x + 1; // only this can possibly be evaluated
}

y = y - 1;

printf("%d %d", x, y);

If you want both expressions x = x + 1 and y = y - 1 to be evaluated, then they both need to be enclosed between braces:

if (n > 0)
{
    x = x + 1;
    y = y - 1;
}

nullptr - Your response is appreciated. Now, you've explained that only the x should be evaluated because of the way the code is written, but the compiler is not working that way and instead when n is set to 1 it's evaluating both x(becomes 2) and y(becomes 0) and when n is 0 it evaluates only y(which becomes 0) and x (remains 1). Would await your response on this one. Thanks.

x=1;  
y=1;

if ( n > 0)
    x = x + 1; // this line will only be evaluated if (n > 0)

y = y - 1;    // this line will always be evaluated regardless of the value of n

Hopefully the comments I've included above will clarify things.

Scudzilla - Any reason behind that ?

If you don't use curly braces, only the command immediately after the if statement will be conditional. Any succeeding commands will not rely on the if statement. If you want more than one command to be conditional, place them in a block (use curly braces).

Edited 3 Years Ago by scudzilla

nullptr and scudzilla - Thank you both for your assistance in explaining the code above.

This question has already been answered. Start a new discussion instead.