Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof(value) vs sizeof(type)?

Considering :

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

Is there a difference between :

sizeof(double);
sizeof(double[10]);
sizeof(std::vector<int>);
sizeof(MyClass);

and

sizeof(data);
sizeof(array);
sizeof(vec);
sizeof(myclass);

Are the two syntaxes different or strictly equivalent ? Are all of them evaluated at compile-time ? If not, which one is evaluated at run-time ?

like image 433
Vincent Avatar asked Oct 10 '12 03:10

Vincent


People also ask

What is the value returned by sizeof int?

So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.

Can you call sizeof on a variable?

3 The sizeof OperatorThe argument to the sizeof operator can be a variable, an array name, the name of a basic data type, the name of a derived data type, or an expression. Remember sizeof is an operator and not a function, even though it looks like a function.

What can I use instead of sizeof in C?

No there is not alternative to sizeof() operator in standard ANSI C. Sizeof() is a compiletime operator can be applied to type too ,i.e. sizeof(int); runtime not call any function so sizeof() is very quick.

What is sizeof () in C?

The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.


1 Answers

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.

like image 124
Jerry Coffin Avatar answered Oct 08 '22 12:10

Jerry Coffin