My program includes the following code:
printf("%8lx", int);
And in kubuntu, when I run the program, it actually prints 16 chars, rather than 8. How is this possible?
My program includes the following code:
printf("%8lx", int);
And in kubuntu, when I run the program, it actually prints 16 chars, rather than 8. How is this possible?
That is correct, depending on the value of the integer. The width specifier is the minimum width, not the maximum width:
"Width: Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger."
it's considered a bad style to use a reserved word int as a variable name – lenik 31 mins ago
It's not just bad style; it's a constraint violation. There's no way this code could compile, let alone produce the symptoms you describe. That aside, if we take time to reconstruct some semblance of an MCVE, and try to compile it, well, first the MCVE...
#include <stdio.h>
int main(void) {
printf("%8lx\n", (int){42});
}
My compiler is warning me... did you see that warning there? In fact, ideone.com flat out refuses to compile and run even this more complete code... It's complaining about format ‘%lx
’ expects argument of type ‘long unsigned int
’, but argument 2 has type ‘int
’... That makes sense, because %lx
tells printf
to expect a long unsigned int
argument, but we've passed printf
an int
instead...
I'd like to attribute to this answer the book K&R2E, for those who are trying to learn without one, as I am legally entitled to do so according to section 4C. b. i. of the Creative Commons Legal Code which governs StackOverflows content license. No matter how unpopular this message may be, it is dangerous to learn C without a book.