Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the size of the data type different when the value is directly passed to the sizeof operator?

Tags:

c

int

sizeof

#include <stdio.h>
int main() {
    char a = 'A';
    int b = 90000;
    float c = 6.5;
    printf("%d ",sizeof(6.5));
    printf("%d ",sizeof(90000));
    printf("%d ",sizeof('A'));
    printf("%d ",sizeof(c));
    printf("%d ",sizeof(b));
    printf("%d",sizeof(a));
    return 0;
}

The output is:

8 4 4 4 4 1

Why is the output different for the same values?

like image 881
j s Avatar asked Dec 10 '19 18:12

j s


People also ask

What is the purpose of the operator sizeof?

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. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.

How does sizeof operator work in C?

The sizeof operator is the most common operator 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.

Why sizeof operator is called the compile-time operator?

If we try to increment the value of x, it remains the same. This is because, x is incremented inside the parentheses and sizeof() is a compile time operator.


1 Answers

Constants, like variables, have a type of their own:

  • 6.5 : A floating point constant of type double
  • 90000 : An integer constant of type int (if int is 32 bits) or long (if int is 16 bits)
  • 'A' : A character constant of type int in C and char in C++

The sizes that are printed are the sizes of the above types.

Also, the result of the sizeof operator has type size_t. So when printing the proper format specifier to use is %zu, not %d.

like image 99
dbush Avatar answered Sep 18 '22 18:09

dbush