C51: INCORRECT OPERATION OF PRINTF AND SIZEOF
Information in this article applies to:
If the sizeof operator is located within a printf statement, a bogus number is printed. For example if x is declared to be an integer,
will print 512. However, the following will print correctly:
unsigned a = sizeof(x); printf("%u", a);
Usually constants (the result of sizeof is a constant) are treated as an integer (the ANSI standard treats constants as integers). In an 8-bit CPU, performance suffers when every number is treated as a integer. Therefore, if a constant number can be represented in a single byte (as a char), the Keil compiler treats it that way. This is even true for the values return by sizeof.
If you pass a constant value to a normal function where the parameter type is known, the parameters are implicitly cast to the required type. Only when the parameter type is not known (var arg '...' parameter in printf) the C compiler assumes that it can pass the constant number as a character. Since printf expects an integer, the output results are incorrect.
The best way to work around this problem is to explicitly cast constant values being passed to printf. For example:
printf("%u", (unsigned int) sizeof(x));
The following Discussion Forum threads may provide information related to this topic.
Last Reviewed: Tuesday, June 8, 2004
of your data.