Today, I encountered a problem when I was reading the programmer's interview book: sizeof the size allocated in the computing stack. When I look at this sentence, I don't understand it. Is it true that the sizeof of variables similar to the static and extern const types in functions are all 0?
Based on the principle of true knowledge, I tested it:
Static int s = 10; Extern const int h = 10; Void main () { Cout <sizeof (s) <endl <sizeof (h) <endl; Getchar (); } |
Output result:
4
4
The result is obviously different from what was mentioned in the book. Read the book carefully and find that the context of this sentence is in the class. Indeed, when sizeof calculates the size of the class, static shared members are not considered.
Class A1 { Public: A1 (): d (10 ){}; Int; Char c; Const int d; Static int B; }; Void main () { A1 x; Int * p = (int *) & (x. d ); * P = 20; Cout <sizeof (A1) <endl; Getchar (); } |
Output result:
12
Although there is a context in the book, I think it is easy to mislead readers. So here, I will describe sizeof based on the information and my own understanding:
The essence of sizeof is to get the size of a certain type. Specifically, it is the size of the space to be allocated when an object (or variable) of this type is created. Classes can also be understood as a Type similar to int and float. When static member variables appear in the class, static member variables are stored in the static zone, it is a shared volume. Therefore, when creating an instance object for this class, you do not need to allocate space for static member variables. Therefore, the space to be allocated for instance objects of this class is to exclude static member variables. Therefore, when sizeof calculates the class size, the size of static member variables is ignored.
According to the above explanation, we can explain why the size obtained by sizeof is not 0 when the static variable is not in the class, because when the static variable is not in the class, when defining a variable for the static type (static int, etc.), space must be allocated. Therefore, sizeof calculates the size of the space allocated for this type of variable.
If you have any questions, please correct them!