Does sizeof operator return different values โ€‹โ€‹for c & c ++?

An array of characters is defined globally, and a structure with the same name is defined inside the function. Why does the sizeof operator return different values โ€‹โ€‹for c and C ++?

char S[13]; void fun() { struct S { int v; }; int v1 = sizeof(S); } 

// returns 4 in C ++ and 13 in C

+6
source share
2 answers

Because in C ++, the struct you define is named S , and in C, it is struct S (so you often see the typedef struct used in C code). If you want to change the code to the following, you will get the expected results:

 char S[13]; void fun() { typedef struct tagS { int v; } S; int v1 = sizeof(S); } 
+15
source

In C, to refer to the type of structure, you must say struct S Therefore, sizeof(S) refers to an array.

In C ++, struct not required. Thus, local S hides global S

+10
source

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


All Articles