0

I have below C code in which I have applied a not operator on a long double variable:

#include <stdio.h>

int main()
{
   long double a;
   signed char b;
   int arr[sizeof(!a+b)];
   printf("\n%d",sizeof(arr));
   return 0;
}

This code outputs 16. I have problem in understanding what happenes when we apply not operator on long double, as we have done with a.

Please help me to understand whats happeneing with this code.

Thank You!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Vipul Tyagi
  • 547
  • 3
  • 11
  • 29

1 Answers1

8

From the C Standard (6.5.3.3 Unary arithmetic operators)

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

So in this expression

sizeof(!a+b)

the sub-expression !a has the type int.

There are used the integer promotions of the operand b to the type int in the expression!a + b because the rank of the type signed char is less than the rank of the type int and the type int can represent all values of the type signed char.

From the C Standard (6.3.1.1 Boolean, characters, and integers)

  1. ...If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. 58) All other types are unchanged by the integer promotions.

So the full expression is equivalent to

sizeof( int )

If the sizeof( int ) is equal to 4 then you have an array declared like

int arr[4];

Its size is equal to 16 that is to 4 * sizeof( int ).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335