sizeof(value) vs sizeof(type)?

前端 未结 3 547
一生所求
一生所求 2021-01-02 23:37

Considering :

double data; 
double array[10]; 
std::vector vec(4, 100); 
MyClass myclass;   

Is there a difference between :

相关标签:
3条回答
  • 2021-01-02 23:46

    The only differences are in syntax and convenience.

    Syntactically, you're allowed to leave out the parentheses in one case, but not the other:

    double d;
    
    sizeof(double); // compiles
    sizeof(d);      // compiles
    sizeof d;       // compiles
    sizeof double;  // does NOT compile
    

    As far as convenience goes, consider something like:

    float a;
    
    x = sizeof(float);
    
    y = sizeof(a);
    

    If, for example, you sometime end up changing a from a float to a double, you'd also need to change sizeof(float) to sizeof(double) to match. If you use sizeof(a) throughout, when you change a from a float to a double, all your uses of sizeof will automatically change too, without any editing. The latter is more often a problem in C than C++, such as when calling malloc:

    float *a = malloc(10 * sizeof(float));
    

    vs.

    float *a = malloc(10 * sizeof(*a));
    

    In the first case, changing the first float to double will produce code that compiles, but has a buffer overrun. In the second case, changing the (only) float to double works fine.

    0 讨论(0)
  • 2021-01-03 00:00

    The latter is defined in terms of the former. Given an expression, it returns the size of the type of the expression. So sizeof(vec) translates to sizeof(std::vector<int>).

    Both are evaluated at compile-time; the only run-time sizeof is in C, not C++, with variable-length arrays. The operand to sizeof is unevaluated, so there isn't any real possibly the expression itself could generate code anyway.

    I prefer to use expressions over types, because chances are stating the type is redundant in some fashion.

    0 讨论(0)
  • 2021-01-03 00:06

    Whenever you use sizeof(<whatever>), it is always evaluated at compile time. It is the datatype of the parameter that sizeof is concerned with.

    However, you can pass values, and even expressions as parameter. But the sizeof function will only consider the dataype of the passed parameter.

    You can also pass expressions as sizeof(x = x+1);. Say x was int. In this case this sizeof will return 4(as on my machine) and the value of x will remain unchanged. This is because sizeof is always evaluated at compile time.

    The two set of syntax you provide, will return the same result, but you cannot say they are equivalent. But yes, latter is defined in terms of former.

    0 讨论(0)
提交回复
热议问题