Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

c - Is the "true" result of >, <, !, &&, || or == defined?

When I for instance write 7>1 in C (say C99 if this is not an always-been feature), can I expect the result will be exactly 1 or just some non-zero value? Does this hold for all bool operators?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In C99 §6.5.8 Relational Operators, item 6 (<,>,<= and >=):

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false) The result has type int.

As for equality operators, it's a bit further in §6.5.9 (== and !=):

The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence) Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. For any pair of operands, exactly one of the relations is true.

The logical AND and logical OR are yet a bit further in §6.5.13 (&&)

The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

... and §6.5.14 (||)

The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

And the semantics of the unary arithmetic operator ! are over at §6.5.3.3/4:

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

Result type is int across the board, with 0 and 1 as possible values. (Unless I missed some.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...