Why use !!(condition) instead of (condition)? [duplicate] - c

This question already has answers here:
What does !!(x) mean in C (esp. the Linux kernel)?
(3 answers)
Closed 9 years ago.
I've seen code where people have used conditional clauses with two '!'s
#define check_bit(var, pos) (!!((var) & (1 << (pos))))
#define likely(x) __builtin_expect(!!(x),1)
#define unlikely(x) __builtin_expect(!!(x),0)
are some of the examples I could find.
Is there any advantage in using !!(condition) over (condition)?

Well if the variable you are applying !! is not already a bool(either zero or one) then it will normalize the value to either 0 or 1.
With respect to __builtin_expect this kernel newbies thread discusses the notation and one of the responses explains (emphasis mine):
The signature of __builtin_expect
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html) is:
long __builtin_expect (long exp, long c)
Note that the exp parameter should be an integral expression, thus no pointers
or floating point types there. The double negation handles the conversion from
these types to integral expressions automatically. This way, you can simply
write: likely(ptr) instead of likely(ptr != NULL).
For reference in C99 bool macro expands to _Bool, true expands to 1 and false expands to 0. The details are given in the draft standard section 7.16 Boolean type and values .
Logical negation is covered in 6.5.3.3 Unary arithmetic operators in paragraph 5:
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).

The unary ! logical negation operator, applied to any scalar, yields the int value 0 if its operand is non-zero, 1 if the operand is equal to zero. Quoting the standard:
The expression !E is equivalent to (0==E).
Applying ! twice to the same scalar value yields a result that's false if the value is false, true if the value is true -- but the result is normalized to 0 or 1, respectively.
In most cases, this isn't necessary, since any scalar value can be used directly as a condition. But in some cases you actually need a 0 or 1 value.
In C99 or later, casting the expression to _Bool (or to bool if you have #include <stdbool.h> behaves similarly and might be considered clearer. But (a) the result is of type _Bool rather than int, and (b) if you're using a pre-C99 compiler that doesn't support _Bool and you've defined your own bool type, it won't behave the same way as C99's _Bool.

The biggest I can see, is that it will force (or normalize) the value into 1 or 0 (that is a boolean value) regardless of how the x or var expression expands (e.g. char or double or int or etc.).

It casts to a boolean, which can sometimes be useful.

Related

how logical NOT operator works in c?

How the logical NOT operator ! actually works in c?
How it turns all non-zero int into 0 and vice-versa?
For example:
#include <stdio.h>
void main() {
if(!(-76))
printf("I won't print anything");
if(!(2))
printf("I will also not print anything");
}
doesn't print anything, which could mean -76 and 2 was turned into zero...
So, I tried this:
#include <stdio.h>
void main() {
int x = !4;
printf("%d", x);
}
which indeed printed 0
and now I don't get how, is it flipping all the bits to 0 or what?
Most CPU architectures include an instruction to compare to zero; or even check the result against zero for most operations run on the processor. How this construct is implemented will differ from compiler to compiler.
For example, in x86, there are two instructions: JZ and JNZ: jump zero and jump not zero, which can be used if your test is an if statement. If the last value looked at was zero, jump (or don't jump) to a new instruction.
Given this, it's trivial to implement int x = !4; at assembly level as a jump if 4 is zero or not, though this particular example would be likely calculated at compile time, since all values are constant.
Additionally, most versions of the x86 instruction set support the SETZ instruction directly, which will set a register directly to 1 or 0, based on whether the processors zero flag is currently set. This can be used to implement the logical NOT operation directly.
6.5.3.3 Unary arithmetic operators
Constraints
1 The operand of the unary + or - operator shall have arithmetic type; of the ~ operator, integer type; of the ! operator, scalar type.
Semantics
...
5 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).
C 202x Working Draft
So, that's what language definition says should happen; if the expression x evaluates to non-zero, then the expression !x should evaluate to zero; if x evaluates to zero, then !x should evaluate to 1. The bits of the operand are not affected.
How that's accomplished in the machine code is up to the specific implementation; it depends on the available instruction set, the compiler, and various other factors such that no one answer works everywhere. It could translate to a branch statement, it could take advantage of specialized instructions, etc.

Why does "sizeof(a ? true : false)" give an output of four bytes?

I have a small piece of code about the sizeof operator with the ternary operator:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool a = true;
printf("%zu\n", sizeof(bool)); // Ok
printf("%zu\n", sizeof(a)); // Ok
printf("%zu\n", sizeof(a ? true : false)); // Why 4?
return 0;
}
Output (GCC):
1
1
4 // Why 4?
But here,
printf("%zu\n", sizeof(a ? true : false)); // Why 4?
the ternary operator returns boolean type and sizeof bool type is 1 byte in C.
Then why does sizeof(a ? true : false) give an output of four bytes?
It's because you have #include <stdbool.h>. That header defines macros true and false to be 1 and 0, so your statement looks like this:
printf("%zu\n", sizeof(a ? 1 : 0)); // Why 4?
sizeof(int) is 4 on your platform.
Here, ternary operator return boolean type,
OK, there's more to that!
In C, the result of this ternary operation is of type int. [notes below (1,2)]
Hence the result is the same as the expression sizeof(int), on your platform.
Note 1: Quoting C11, chapter §7.18, Boolean type and values <stdbool.h>
[....] The remaining three macros are suitable for use in #if preprocessing directives. They
are
true
which expands to the integer constant 1,
false
which expands to the integer constant 0, [....]
Note 2: For conditional operator, chapter §6.5.15, (emphasis mine)
The first operand is evaluated; there is a sequence point between its evaluation and the
evaluation of the second or third operand (whichever is evaluated). The second operand
is evaluated only if the first compares unequal to 0; the third operand is evaluated only if
the first compares equal to 0; the result is the value of the second or third operand
(whichever is evaluated), [...]
and
If both the second and third operands have arithmetic type, the result type that would be
determined by the usual arithmetic conversions, were they applied to those two operands,
is the type of the result. [....]
hence, the result will be of type integer and because of the value range, the constants are precisely of type int.
That said, a generic advice, int main() should better be int main (void) to be truly standard-conforming.
The ternary operator is a red herring.
printf("%zu\n", sizeof(true));
prints 4 (or whatever sizeof(int) is on your platform).
The following assumes that bool is a synonym for char or a similar type of size 1, and int is larger than char.
The reason why sizeof(true) != sizeof(bool) and sizeof(true) == sizeof(int) is simply because true is not an expression of type bool. It's an expression of type int. It is #defined as 1 in stdbool.h.
There are no rvalues of type bool in C at all. Every such rvalue is immediately promoted to int, even when used as an argument to sizeof. Edit: this paragraph is not true, arguments to sizeof don't get promoted to int. This doesn't affect any of the conclusions though.
Regarding the boolean type in C
A boolean type was introduced fairly late in the C language, in the year 1999. Before then, C did not have a boolean type but instead used int for all boolean expressions. Therefore all logical operators such as > == ! etc return an int of value 1 or 0.
It was custom for applications to use home-made types such as typedef enum { FALSE, TRUE } BOOL;, which also boils down to int-sized types.
C++ had a much better, and explicit boolean type, bool, which was no larger than 1 byte. While the boolean types or expressions in C would end up as 4 bytes in the worst case. Some manner of compatibility with C++ was introduced in C with the C99 standard. C then got a boolean type _Bool and also the header stdbool.h.
stdbool.h provides some compatibility with C++. This header defines the macro bool (same spelling as C++ keyword) that expands to _Bool, a type which is a small integer type, likely 1 byte large. Similarly, the header provides two macros true and false, same spelling as C++ keywords, but with backward compatibility to older C programs. Therefore true and false expand to 1 and 0 in C and their type is int. These macros are not actually of the boolean type like the corresponding C++ keywords would be.
Similarly, for backward compatibility purposes, logical operators in C still return an int to this day, even though C nowadays got a boolean type. While in C++, logical operators return a bool. Thus an expression such as sizeof(a == b) will give the size of an int in C, but the size of a bool in C++.
Regarding the conditional operator ?:
The conditional operator ?: is a weird operator with a couple of quirks. It is a common mistake to believe that it is 100% equivalent to if() { } else {}. Not quite.
There is a sequence point between the evaluation of the 1st and the 2nd or 3rd operand. The ?: operator is guaranteed to only evaluate either the 2nd or the 3rd operand, so it can't execute any side-effects of the operand that is not evaluated. Code like true? func1() : func2() will not execute func2(). So far, so good.
However, there is a special rule stating that the 2nd and 3rd operand must get implicitly type promoted and balanced against each other with the usual arithmetic conversions. (Implicit type promotion rules in C explained here). This means that the 2nd or 3rd operand will always be at least as large as an int.
So it doesn't matter that true and false happen to be of type int in C because the expression would always give at least the size of an int no matter.
Even if you would rewrite the expression to sizeof(a ? (bool)true : (bool)false) it would still return the size of an int !
This is because of implicit type promotion through the usual arithmetic conversions.
Quick answer:
sizeof(a ? true : false) evaluates to 4 because true and false are defined in <stdbool.h> as 1 and 0 respectively, so the expression expands to sizeof(a ? 1 : 0) which is an integer expression with type int, that occupies 4 bytes on your platform. For the same reason, sizeof(true) would also evaluate to 4 on your system.
Note however that:
sizeof(a ? a : a) also evaluates to 4 because the ternary operator performs the integer promotions on its second and third operands if these are integer expressions. The same of course happens for sizeof(a ? true : false) and sizeof(a ? (bool)true : (bool)false), but casting the whole expression as bool behaves as expected: sizeof((bool)(a ? true : false)) -> 1.
also note that comparison operators evaluate to boolean values 1 or 0, but have int type: sizeof(a == a) -> 4.
The only operators that keep the boolean nature of a would be:
the comma operator: both sizeof(a, a) and sizeof(true, a) evaluate to 1 at compile time.
the assignment operators: both sizeof(a = a) and sizeof(a = true) have a value of 1.
the increment operators: sizeof(a++) -> 1
Finally, all of the above applies to C only: C++ has different semantics regarding the bool type, boolean values true and false, comparison operators and the ternary operator: all of these sizeof() expressions evaluate to 1 in C++.
Here is a snippet from which is what included in the source
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#else /* __cplusplus */
There macros true and false are declared as 1 and 0 respectively.
however in this case the type is the type of the literal constants. Both 0 and 1 are integer constants that fit in an int, so their type is int.
and the sizeof(int) in your case is 4.
There is no boolean datatype in C, instead logical expressions evaluate to integer values 1 when true otherwise 0.
Conditional expressions like if, for, while, or c ? a : b expect an integer, if the number is non-zero it's considered true except for some special cases, here's a recursive sum function in which the ternary-operator will evaluate true until n reach 0.
int sum (int n) { return n ? n+sum(n-1) : n ;
It can also be used to NULL check a pointer, here's a recursive function that print the content of a Singly-Linked-List.
void print(sll * n){ printf("%d -> ",n->val); if(n->next)print(n->next); }

Return value of a boolean expression in C

For reasons that are not worth mentioning, I want to know if there's a standard defined value for boolean expressions. E.g.
int foo () {
return (bar > 5);
}
The context is that I'm concerned that our team defined TRUE as something different than 1, and I'm concerned that someone may do:
if (foo() == TRUE) { /* do stuff */ }
I know that the best option would be to simply do
if (foo())
but you never know.
Is there a defined standard value for boolean expressions or is it up to the compiler? If there is, is the standard value something included in C99? what about C89?
An operator such as ==, !=, &&, and || that results in a boolean value will evaluate to 1 of the expression is true and 0 if the expression is false. The type of this expressing is int.
So if the TRUE macro is not defined as 1, a comparison such as the above will fail.
When an expression is evaluated in a boolean context, 0 evaluates to false and non-zero evaluates to true. So to be safe, TRUE should be defined as:
#define TRUE (!0)
As was mentioned in the comments, if your compiler is C99 compliant, you can #include <stdbool.h> and use true and false.
According to C99:
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).
6.5.8 (Relational operators)
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.
6.5.9 (Equality operators)
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.
6.5.13 (Logical AND operator)
The && operator shall yield 1 if both of its operands compare
unequal to 0; otherwise, it yields 0. The result has type int.
6.5.14 (Logical OR operator)
The || operator shall yield 1 if either of its operands compare
unequal to 0; otherwise, it yields 0. The result has type int.
The C programming language does not define Boolean value. Traditionally, the C programming language uses integer types to represent boolean data types.
Boolean values in C:
0 = false`
Any other value = true`
Usually people will use 1 for true.
C99 introduced the_Bool data type that is not available in other C derivates.See wikipedia link here. Additionally, a new header stdbool.h has been added for compatibility reasons. This header allows programmers to use boolean types in the same way, as in C++ language.
To use bool in C, we can use enum as below.
enum bool {
false, true
};
bool value;
value = bool(0); // False
value = bool(1); // True
if(value == false)
printf("Value is false");
else
printf("Value is true");
Also, related Stack overflow question
Is bool a native C type?

Usage of NOT operator in #define directives in C programming

I have defined macros as below.
#define FALSE 0
#define TRUE (!FALSE)
What will be the data-type of TRUE and FALSE? What literal value does TRUE take after preprocessing? Is it compiler dependent? Why?
#define preprocessor directive (macros) are meant to do textual replacement. It will replace all occurrence of FALSE to 0 and TRUE to !0 that essentially gets evaluated to 1. So, the resultant data type will be same as 0 and 1. i.e., integer.
Regarding the usage of ! operator, it always produces a result of type int.
Quoting the C11 standard, chapter §6.5.3.3 (emphasis mine)
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. [...]
At the time of preprocessing, macros are replaced with text.
FALSE will be replace by 0, and TRUE will be replaced by 1.

double negation in C : is it guaranteed to return 0/1?

Is !!(x) guaranteed by the standard to return 0/1?
Note that I am not asking about c++, where a bool type is defined.
Yes, in C99, see §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).
So !x and !!y can only yield 0 or 1, as ints.
For other operators, in C99, see also Is the "true" result of >, <, !, &&, || or == defined?
This is a comment really, but it's too long.
I found a very bizarre document while looking for the standard to answer your question: The New C Standard: An Economic and Cultural Commentary. And they say academia is under-funded. (Here is the full, 2083 page 10.5MB PDF. The former link is just the section on double negation.)
It has this to say on the subject of double negation:
A double negative is very often interpreted as a positive statement in English (e.g., “It is not unknown for double negatives to occur in C source”). The same semantics that apply in C. However, in some languages (e.g., Spanish) a double negative is interpreted as making the statement more negative (this usage does occur in casual English speech, e.g., “you haven’t seen nothing yet”, but it is rare and frowned on socially1).
I believe that the author would be happy knowing that this is of no use whatsoever in answering your real question (the answer to which is yes.)

Resources