Is logical negation of zero (!0) compiler dependent in C?
Asked Answered
S

2

4

I came across an article which mentioned that the result of !0 is compiler dependent. The result can be either 1 or FF or FFFF and so on.

As for C99 standard 6.5.3.3 Unary arithmetic operators,

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).

Is it really compiler dependent?

Sext answered 30/10, 2011 at 15:50 Comment(2)
Didn't you quote the standard that says it evaluates to 1?! So it should be platform/compiler independent. Maybe that article meant to say ~0 is platform dependent.Passacaglia
Where did you come across that article?Grandfather
T
10

You seem to have answered you own question already, quoting from the standard where it specifies that the result must be 0 or 1.

As such, about all I can guess is that you're asking whether all C compilers conform with the standard in this respect. Since I haven't used every C compiler ever written, I can't really answer that definitively. I've never used or heard of one that produced any other value though -- and given the years I've spent hanging out here, on Usenet, etc., it seems likely that if such a beast existed I'd probably have heard of it.

Edit: It's probably worth noting that even in K&R1, it's specifically described as producing 0 or 1 (§A.7.2):

The result of the logical negation operator ! is 1 if the value of its operand is 0, 0 if the value of its operand is non-zero.

Trawler answered 30/10, 2011 at 16:1 Comment(0)
C
1

Each compiler should have in their description a list of standards they follow. Of course this description is not always totally true (some compiler contains bug or misinterpretation of the standards), but that behaviour with boolean is so simple and so old (comes from first day of C) that I would be really surprised if a new compiler behave differently.

So I always got it as a official standard and also a de-facto standard: (!0) = 1 and (!1) = 0, both of type int.

Be careful however that in C++ boolean operators returns a bool value, so if you compile in C++, bool will be used, not int. However bool and int are directly interchangeable, except the fact that some C++ compiler will warn you if you do something strange, like bool x = 10;.

Cicily answered 30/10, 2011 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.