#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.
4
8
Can someone explain why the difference?
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, .
sizeof(::T)
T
::T
C (//) (//typedefs) , , .
struct T T;
, , , - .
++, .
hacck. , , C ++ - , .
, C ++ - .
++, ( ),
struct T { double x; };
T sobj; // sobj is an object of type T
T - . C, T , struct T
struct T
struct T sobj;
sizeof(T) sizeof(struct T) ++ sizeof(struct T) C, .
sizeof(T)
sizeof(struct T)
C, T struct T struct. Struct , . C, struct T.
sizeof() , , struct . T. sizeof().
sizeof()
++ T in struct T - , ++ public. sizeof(T) struct ++.
, sizeof :
sizeof
sizeofsizeof (-)
, sizeof , . . , sizeof T sizeof (T), ++, T , .
sizeof T
sizeof (T)
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.
Source: https://habr.com/ru/post/1689441/More articles:Why is it faster to set an empty src attribute than not to put it? - javascriptReactorNettyWebSocketClient Usage Examples - spring-bootThrow an exception ObservableCollection - exceptionCopyMemory crashes Excel application - vbaiPhone-X - How to get the user to double-scroll the home indicator to go to the main screen - iosWhat is the difference between func () => {} and func = () => {} in a class? - javascriptHow to make GCC warn about using a class function? - c ++https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1689444/java-gc-runs-too-often-even-if-huge-memory-is-available&usg=ALkJrhh6mJZLoPRvDgumlcHaTAX7J62Lkgcompose () vs. transform () vs. as () vs. map () in Flux and Mono - reactive-programmingFind two rectangles with minimal areas that span all points - algorithmAll Articles