简体   繁体   中英

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?

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.

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?

Because, with a very few exceptions, the sizeof operator does not evaluate its operand. Your usage is not one of the exceptions. Not evaluating getchar() means getchar() is not called.

In any event, I'm not sure what you expect from your code. Even if getchar() were called, the result always has the same type ( int ), which does not depend on the input.

Do also pay attention to @PP's comments. Your printf() format does not match the type of the data being printed, size_t . As he observes, the printf() call has undefined behavior as a result.

Because getchar() return type is an int , not a char . sizeof(int) is 4 on your platform.

Also, you should use %zu to print size_t values. Using incorrect format specifier is technically undefined behaviour .

In C the sizeof operator is evaluated at run-time only for Variable Size Arrays (VLA). In all other cases the operator does nor evaluate its operand. It deduces the type of the expression and returns the size of object of the deduced type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM