Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the working of sizeof operator different in c andd c++ [duplicate]

Tags:

c++

c

I have written a small printf statement which is working different in C and C++:

    int i;
    printf ("%d %d %d %d %d \n", sizeof(i), sizeof('A'), sizeof(sizeof('A')),    sizeof(float), sizeof(3.14));

The output for the above program in c using gcc compiler is 4 4 8 4 8

The output for the above program in c++ using g++ compiler is 4 1 8 4 8

I expected 4 1 4 4 8 in c. But the result is not so.

The third parameter in the printf sizeof(sizeof('A')) is giving 8

Can anyone give me the reasoning for this

like image 251
Kranthi Kumar Avatar asked Apr 12 '13 04:04

Kranthi Kumar


People also ask

How sizeof operator works in C?

It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

What is the output of sizeof?

When applied to arrays, sizeof returns the size of the array in bytes. For example, sizeof(int[10]) returns 40 on a machine where sizeof(int) is 4. Since sizeof(char) is 1, it will equal the amount of characters in a string literal.

What is sizeof int in C?

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.

What type of value sizeof return?

The sizeof operator is used to get the size of types or variable in bytes. Returns an unsigned integer type of at least 16 bit.


1 Answers

It's nothing to do with the sizeof operator in particular; rather, the size of character literals in C is different than C++, because character literals in C are of type int, whereas in C++ they are of type char.

See Why are C character literals ints instead of chars? for more information.

like image 139
Charles Salvia Avatar answered Oct 08 '22 17:10

Charles Salvia