A three point analysis of sizeof detail in C

  • 2020-04-02 01:07:51
  • OfStack

Sizeof is an operator, which is the same as addition, subtraction, multiplication and division, and is executed at compile time, not at run time.
So what if you verify that in your programming? Ps: this is a question from my friend's taobao interview two days ago.


#include<iostream> 

using namespace std; 

int main() 
{ 
    int i=1; 
    cout<<i<<endl; 
    sizeof(++i); 
    cout<<i<<endl; 
    return 1; 
}

The input result is 1    
                            1
The side effect of ++ I in sizeof is not shown, there is only one possible reason, the side effect of ++ I was processed after sizeof was executed at compile time, so the side effect of ++ I was eliminated. If sizeof is done at run time, you should definitely pay attention to ++ I. Actually the implementation of sizeof should be done with macros, which are executed at compile time. Specific implementation can refer to the following.

2. Sizeof ('a') results in 4 in C and 1 in C++. I read an article that said sizeof in C focuses on "Numbers", while sizeof in C++ focuses on "characters".

3. Two classic applications of sizeof with macros are described in the article


//Applies to non-arrays
#define _sizeof(T) ((size_t)((T*)0 + 1)) 
//For arrays
#define array_sizeof(T) ((size_t)(&T+1)-(size_t)(&T)) 

Two small examples of two macros are given, for the first example, _sizeof(int); The result is 4; For the second, first declare an array int a[4] of size 4. So array_sizeof(a) is equal to 16.

For a non-array macro definition, you first convert 0 to the address to which a pointer of type T* points (at this point, the address is 0). Then add 1 to the address of type T, which is equivalent to adding the size of type T. The previous size_t just returns the address as an int.

A simple example: int* p; P = p + 1; --p is an int* pointer, and p+1 adds four bytes to the address space.

For the macro definition of the array, similar to the macro definition of the non-array, for the sake of understanding, you can think of the array T as a user-defined type, &T represents the pointer to the array type, for the array type pointer plus 1 is equivalent to adding the array size to the address. Since it is a user-defined type, you cannot force 0 to be converted to an address of array type. You can only subtract the previous address from the address after adding 1, and the difference is the size of the byte occupied by the array itself.


Related articles: