linux - [Solved-4 Solutions] What is “:-!!” in C code ? - ubuntu - red hat - debian - linux server - linux pc



Problem :

What is “:-!!” in C code ?

Linux - Solution 1:

Expression

sizeof(struct { int: -!!(e); }))
click below button to copy the code. By - Linux tutorial - team
  • (e): Compute expression e.
  • !!(e): Logically negate twice: 0 if e == 0; otherwise 1.
  • -!!(e): Numerically negate the expression from step 2: 0 if it was 0; otherwise -1.
  • struct{int: -!!(0);} --> struct{int: 0;}: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.
  • struct{int: -!!(1);} --> struct{int: -1;}: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.

Linux - Solution 2:

  • The : is a bitfield.
  • As for !!, that is logical double negation and so returns 0 for false or 1 for true. And the - is a minus sign, i.e. arithmetic negation.
  • It's all just a trick to get the compiler to barf on invalid inputs.
  • Consider BUILD_BUG_ON_ZERO.
    • When -!!(e) evaluates to a negative value, that produces a compile error.
    • Otherwise -!!(e) evaluates to 0, and a 0 width bitfield has size of 0. Hence the macro evaluates to a size_t with value 0.
  • BUILD_BUG_ON_NULL is very similar, but yields a pointer rather than an int.

Linux - Solution 3:

Some people have seem to be confusing these macros with assert().

  • These macros are implement a compile-time test, while assert() is a runtime test.

Linux - Solution 4:

  • It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero.
  • In the former case, there is no error and the struct is initialized with an int member.

Related Searches to - linux - linux tutorial - What is “:-!!” in C code ?