Newbie Questions on If statement

Y

Yue

Hi, all,

I know this is too simple...but can somebody tell me:


any expression other than "0" is of boolean "true" type


so: if (x) {} is equivalent to if(x != 0) (1. it has to be a "true"
boolean within if bracket?)


2. if I want the expression to return false in the if bracket, I just
need to write a single "0" or "x=0"


Thanks very much!


yue
 
D

Daniel T.

Yue said:
I know this is too simple...but can somebody tell me:

any expression other than "0" is of boolean "true" type

so: if (x) {} is equivalent to if(x != 0) (1. it has to be a "true"
boolean within if bracket?)

2. if I want the expression to return false in the if bracket, I just
need to write a single "0" or "x=0"

If I understand you correctly, you understand the if statement.

However, you generally don't want to do assignments inside the
expression of an 'if' statement. Things can get pretty muddled pretty
fast that way.
 
R

Ron Natalie

Yue said:
so: if (x) {} is equivalent to if(x != 0) (1. it has to be a "true"
boolean within if bracket?)

Yes provided x isn't some odd type that has overloads for != that do
nonobvious things.
2. if I want the expression to return false in the if bracket, I just
need to write a single "0" or "x=0"
if(0) and if(false) mean the same thing.
if(x=0) will evaluate to false, but has the side effect of setting x
to zero as well.

if(x==0) is the moral equivelent of writing if(!x) (again it can be
thwarted by classes that overload == or ! in non obvious ways).
 
D

Dave Rahardja

so: if (x) {} is equivalent to if(x != 0) (1. it has to be a "true"
boolean within if bracket?)

For POD types, yes. For user-defined types (classes), generally, no.

-dr
 
R

Rahul

For POD types, yes. For user-defined types (classes), generally, no.

-dr

user-defined types would work if they have an operator function, which
converts the user-defined type to a bool type...
 
Y

Yue

if(x==0) is the moral equivelent of writing if(!x)  (again it can be
thwarted by classes that overload == or ! in non obvious ways).

thank you for your reply, Ron.
Does that mean by default, x is a non-zero value?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top