Search code examples
cprintfsizeof

Why doesn't sizeof work as expected?


#include <stdio.h> 

int main(void) 
{   
    printf("%d", sizeof (getchar()) );
}

What I expect is,
1. Type input.
2. Read input and return input value.
3. Evaluate sizeof value.
4. Print the sizeof value.

But the first step never happens.

Why doesn't the first step happen?


Solution

  • The sizeof operator does not evaluate its operand unless its type is a variable length array type: It looks at the type and returns the size. This is perfectly safe:

    char *ptr = NULL; // NULL ponter!
    printf("%zu", sizeof *ptr);
    

    It will return 1, since it does not have to evaluate the expression to know the answer.