Can u explain this code.

+2 ♦Avishka RJ ♦™ · March 27, 2015

int x=0;
if(x++)
        cout<<"true"<<endl;
else
        cout<<"False"<<endl;

return 0;
}




There's no condition inside if() so how it become false for 0 and become true for other values??

Post a Reply

Replies

Oldest  Newest  Rating
+2 c student · March 27, 2015
The x++ increments the value of x after the operation has been performed.  In this case, the psuedo code would be:
if x is not 0
print "true"
else
print "false"
increment x

If you wanted to increment x before the operation, you would use ++x instead.
increment x
if x is not 0
print "true"
else
print "false"
+1 James Juan · March 27, 2015
, .basically conditions return 2 values. 0 for FALSE and 1 for TRUE. 

so if(x++) when simplified means if(0) which means false.  it also means if(false).

if you are trying to increment the value of x before evaluating the condition, use ++x instead. this time the value of x will become 1 and 1. and any number other than 0 when dealing with conditional expressions means TRUE.

i hope this helps..:)
0 c student · March 27, 2015
@James Juan
Just to clarify, if statements do not return anything, they compare values and set the flags register accordingly where a corresponding jump command is called to jump to the appropriate location.  Returning is a different case where you would pop off a value from a stack into a register and control would be pointed back to the function which called it.
0 James Juan · March 27, 2015
@ c student.
, . yeah i get the point but i'm not saying it is the  if statement that returns a value.
i said "conditions" and conditional expressions i think return either true or false which is 1 or 0.

im sorry for the confusion

:)
0 c student · March 27, 2015
@James Juan
I see what you mean, however, no value is returned from the expression.  The variables are directly manipulated and compared.
0 James Juan · March 27, 2015
, .yeah yeah.:)  but then those variables can become condition because their result evaluates to an integer value which now can be determined to being true or false right? 

True,  Yes, On = 1 or any number not equal or less than 0
False, No, Off = 0
0 c student · March 27, 2015
Yes, any non-zero number is true.
0 James Juan · March 27, 2015
then the problem is pretty much answered.. :)
  • 1

C++

107,131 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator