Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator sizeof() in C

Tags:

c

types

sizeof

Consider the program

main()  
{  
 printf("%d %d %d",sizeof('3'),sizeof("3"),sizeof(3));  
}

output from a gcc compiler is:

4 2 4

Why is it so?

like image 205
Mohit Avatar asked Jul 26 '10 11:07

Mohit


People also ask

What is the use of sizeof () operator?

You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.

What is sizeof () in C with example?

Need of sizeof() operator Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator: int *ptr=malloc(10*sizeof(int));

What is the type of sizeof in C?

sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of char-sized units. Consequently, the construct sizeof (char) is guaranteed to be 1.

Is sizeof an operator or function?

In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator. For example in the following program, when we pass a++ to sizeof, the expression “a++” is not evaluated. However in case of functions, parameters are first evaluated, then passed to function.


2 Answers

Assuming you are running on a 32-bit system:

sizeof a character literal '3' is 4 because character literals are ints in C language (but not C++).

sizeof "3" is 2 because it is an array literal with length 2 (numeral 3 plus NULL terminator).

sizeof literal 3 is 4 because it is an int.

like image 119
Amardeep AC9MF Avatar answered Sep 28 '22 12:09

Amardeep AC9MF


A few points to keep in mind:

  1. sizeof isn't a function, it's an operator. It returns the size of a type in units of sizeof char. In other words sizeof char is always 1.
  2. '3' is an int
  3. "3" is a char[2], the character 3 then the null terminator.
  4. 3 is an int

With these the differences are easily explained:

  1. an int requires 4 chars of space to hold it
  2. char[2] naturally only requires 2 chars
like image 39
freespace Avatar answered Sep 28 '22 12:09

freespace