Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof operator returns different values for c & c++?

Tags:

c++

c

A character array is defined globally and a structure with same name is defined within a function. Why sizeof operator returns different values for c & c++ ?

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

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

like image 312
Ashwyn Avatar asked May 20 '12 02:05

Ashwyn


2 Answers

Because in C++, the struct you defined is named S, while in C, it's named struct S (which is why you often see typedef struct used in C code). If you were to change the code to the following, you would get the expected results:

char S[13];
void fun()
{
    typedef struct tagS
    {
        int v;
    } S;
    int v1 = sizeof(S);
}
like image 188
Adam Maras Avatar answered Oct 13 '22 00:10

Adam Maras


In C, to refer to the struct type, you need to say struct S. Therefore, sizeof(S) refers to the array.

In C++, struct is unnecessary. So the local S hides the global S.

like image 26
Oliver Charlesworth Avatar answered Oct 12 '22 23:10

Oliver Charlesworth