why?

M

Martin Ambuhl

xcm said:
#include<stdio.h>
main()
{ printf("%d %d\n",sizeof('a'),sizeof('A'));}

why does it printf 2 2 in tc.

Since sizeof() yields an unsigned type (size_t), the "%d" specifier is
incorrect. The reason that sizeof('x') is 2 in your implementation is
that 'a' is an int, and sizeof(int) is 2 in your implementation. You
would get a different result in a very similar language, C++.
 
P

Peter Nilsson

Martin said:
Since sizeof() yields an unsigned type (size_t), the "%d" specifier
is incorrect.

Not if size_t is unsigned short (unlikely), and though it's not
explicit (or at least normative) within the standard, the committee
has advised the intent is that corresponding signed and unsigned
types may be passed in this way, so long as the value being passed
is within the range of both types.

You are unlikely to find an implementation where...

sizeof(int) > INT_MAX

The real problem with the code is that size_t may be an unsigned long.

C90 suffers the problem that there is no length modifier specifically
for size_t. [C99 introduced z, as in %zu.]
The reason that sizeof('x') is 2 in your implementation is
that 'a' is an int, and sizeof(int) is 2 in your implementation.
You would get a different result in a very similar language, C++.

Although the implicit int declaration in the code above would likely
fail to compile in that similar language. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top