Why is the size of the same identifier different in C and C ++?

#include <stdio.h>
int T;
int main()
{
    struct T { double x; };  
    printf("%zu", sizeof(T));
    return 0;
}

If I run this code in C, the result will be 4, and in C ++ - 8.

Can someone explain why the difference?

+4
source share
4 answers

Short answer: Because they are not the same identifier. Actually.

In C, structure names and variable names fall into different namespaces , so in C,

sizeof(T) == sizeof(int) // global variable T
sizeof(struct T) == sizeof(struct T) // not the same namespace

However, in C ++, structure / class names go into the same namespace as variables. the "closest" (most local) name is the result of a name search , so now

sizeof(T) == sizeof(struct T) // structure T
sizeof(::T) == sizeof(int) // Note the scope resolution operator

4 8 .

++ 4 sizeof(::T). T , ::T - int, .


C (//) (//typedefs) , , .

struct T T;

, , , - .

++, .


hacck. , , C ++ - , .

+16

, C ++ - .

++, ( ),

struct T { 
    double x; 
};  

T sobj;  // sobj is an object of type T

T - . C, T , struct T

struct T sobj; 

sizeof(T) sizeof(struct T) ++ sizeof(struct T) C, .

+4

C, T struct T struct. Struct , . C, struct T.

sizeof() , , struct . T. sizeof().

++ T in struct T - , ++ public. sizeof(T) struct ++.


, sizeof :

sizeof
sizeof (-)

, sizeof , . . , sizeof T sizeof (T), ++, T , .

+3

I believe in C to refer to the structure you need to write struct T, while in C ++, since the structure is a public class, it can be called simply T So, both of them take the most local definition Tthat they have.

+2
source

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


All Articles