Jin
Jin

Reputation: 1948

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?

Upvotes: 1

Views: 505

Answers (4)

John Burger
John Burger

Reputation: 3672

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.

Upvotes: 4

P.P
P.P

Reputation: 121347

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.

Upvotes: 1

John Bollinger
John Bollinger

Reputation: 180048

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 @P.P.'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.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

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.

Upvotes: 1

Related Questions