Simple Code Walkthrough


I don't understand how this is true. Could someone please do a code walk through for this, it would be much appreciated!

"The following code will cause 0 (zero) and then ten (10) to be printed."

int x = 12;
if (x = 0);
cout << x;
cout << 10;

X == 0 and
X = 0

Are two different things. The first checks if the memory location labeled x is equivelant to 0,
The second assigns the value of 0 to the memory location labeled x.

Unless there's a problem, the second always returns true.

Do in this code statement
If(x = 0) //true
cout<<x; //print the value of x, which is zero.

The difference is
if(x == 0) //false in this case
cout<<x;// does not print the value of x
Last edited on
x = 0 will return the value of x after the assignment, which is 0.

When an integer is used where a bool is expected 0 is treated as false and everything else is treated as true. Here it doesn't really matter because the statement that is part of the if statement is the semicolon at the end of the line which is an empty statement (statement that does nothing).

cout << x; is not part of the if statement so it will be executed.
Last edited on
Thanks for the help guys, I understand!
if (x = 0);

X=0 assigns the value of 0 to the memory location labeled x.

don not misuse the ";" .
Topic archived. No new replies allowed.