ARM Technical Support Knowledge Articles

INCORRECT OPERATION OF PRINTF AND SIZEOF

Applies to: C51 C Compiler

Answer

Information in this article applies to:


SYMPTOMS

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,

printf("%u", sizeof(x));

will print 512. However, the following will print correctly:

unsigned a = sizeof(x);
printf("%u", a);

CAUSE

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.

RESOLUTION

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));

Article last edited on: 2004-06-08 10:25:52

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential