Sizeof (bitfield_type) legal in ANSI C?

struct foo { unsigned x:1; } f;
printf("%d\n", (int)sizeof(f.x = 1));

What is the expected result and why? The use of the lvalue bit field size is not allowed. But using the assignment operator, it seems that we can still take the size of the bit field type.

What is the size of the bit field in bytes? Is this the size of the storage unit in which the bitfield is located? Is this the number of bits occupied by the bf counter, rounded to the nearest byte?

Or is the constructor behavior undefined because there is nothing in the standard that answers the above questions? Several compilers on the same platform give me inconsistent results.

+3
source share
13 answers

You are right, whole promotions do not apply to the operand sizeof:

: , , +, - ~ , .

, .

:

C90 DRs , , C99 DRs , , GCC C90 DR int: 1 sizeof.

# 315.

: , .

+3

C99 (PDF ) 6.5.3.4 sizeof :

sizeof , , , .

, sizeof .

6.5.16.3 :

- ...

6.3.1.1.2 :

: int/unsigned int :

  • ...
  • _Bool, int, signed int unsigned int.

int , int; unsigned int.

, int, .. sizeof(int).

- , ?

+3

, . (sizeof , .)

sizeof(f.x = 1) . C " ", (: ) unsigned int, ( , , unsigned char, ).

+1

(f.x = 1)

- , true ( , 1/) , ,

sizeof( f.x = 1)

, ?

, sizeof . , : "sizeof - , , char, , ."

, sizeof .

0
sizeof( f.x = 1)

1 . Sizeof (1), , , , , 4 8 .

0

, ==, "" int C bool ++.

, 1 . , .

, .

, "f.x = 1" lvalue, . "unsigned: 1".

"f.x = 1", "sizeof f.x" -, .

0

(f.x = 1)

, , , . , .

unsigned x:1

1 1 ( 8 )

unsigned x:12

sizeof (f.x = 1) 2 ( - 8- )

0

of (1), -, , , , 4 8 .

, sizeof (1), sizeof (int). , sizeof (f.x = 1), sizeof (bitfield_type).

, , . , , .

gcc , sizeof (bitfield_type) , sizeof (int), .

0

, . (sizeof , .)

, , undefined, ​​ , "* (int *) 0 = 0;", ?

, . , undefined -, ?

0

, , , . , .

-, IS , .

-, , :)

sizeof (f.x = 1) 2 ( - 8- )

? , , , , ? . , .

0

,

struct foo { unsigned x:12} f;

1 f.x - 2 - .

f.x = 1;

.

int a, b, c;
a = b = c = 1;

. c = 1 1 c, b ( ..), 1

a = ( b = ( c = 1 ) )

sizeof , NOT , .

sizeof ( f.x = 1)

, , 12- 1 ( ), sizeof() 2 (- 8- )

0

, , .

, , , . .

, , sizeof (int) sizeof (char) EVEN, , .

, . , .

, GUARANTEED .

0

CL, , , , .

6.3.1.1.2 :

, , . , . ,

char ch;
sizeof ch;

... ch .

, .

I also saw gcc output 1, while many other compilers (and even other versions of gcc) do not. This does not convince me that the code is illegal , because the size may be just enough for implementation to make the result inconsistent for several compilers.

However, I am confused as to whether the code can be undefined, because nothing in the standard indicates how the sizeof case of a bit field is handled.

0
source

Source: https://habr.com/ru/post/1697035/


All Articles