http://www.velocityreviews.com/forums/(E-Mail Removed) writes:

> On May 13, 8:00*pm, Eric Sosman <(E-Mail Removed)> wrote:

>> (E-Mail Removed) wrote:

>> > In the following C code snippet

>>

>> > int i=2,j=-1,k=-1,z;

>> > x = ++i || ++j && ++k;

>>

>> > here the right side of || is not evaluated because ++i is a non zero

>> > value( || is short circuit evaluating operator)...

>>

>> > But will the value of x be always 1????

>>

>> * * *Yes, if `x' is a variable of a type that can hold the value `1'.

>> If `x' is a `char*' or a `struct tm' or a `union foobar', or a

>> `signed int : 1' bit-field, then No.

>

> My mistake 'z' was rather 'x'

>

> int i=2,j=-1,k=-1,x;

> x = ++i || ++j && ++k;

>

> I mean to say... the value returned by the left sub-expression (++i ||

> ++j && ++k; ) is true in this case....

>

> Does true always mean '1'????
Yes and no.

In a conditional context (if, while, do-while, second clause of a for

loop, etc.), any expression that compares equal to 0 is treated as

false, and any expression that compares unequal to 0 (not just 1) is

treated as true. So this:

if (0) puts("0");

if (1) puts("1");

if (2) puts("2");

will print "1" and "2".

But a relational or equality operator (<, >, <=, >=, ==, !=), or a

logical operator (!, &&, ||) always yields either 0 or 1; they will

never yield any non-zero value other than 1.

But be careful about depending in this fact. Things other than

operators can yield boolean results, but those results aren't

necessarily normalized to 0 or 1. For example, the is*() functions

declared in <ctype.h> can return any non-zero value to indicate a true

condition.

You can define your own "false" and "true" symbols as 0 and 1,

respectively (or use the "bool" type in <stdbool.h> if your

implementation supports it), but you should be careful how you use

them. For example, this:

if (condition == true) ...

is dangerous, since condition could be true without being equal to 1.

Instead, just write:

if (condition) ...

--

Keith Thompson (The_Other_Keith)

(E-Mail Removed) <http://www.ghoti.net/~kst>

Nokia

"We must do something. This is something. Therefore, we must do this."

-- Antony Jay and Jonathan Lynn, "Yes Minister"