'What does the %# flag in a printf statement in C? [duplicate]
I am doing the chapter 3 of the book learning C the hard way by Zed Shaw. I am exploring the different string formatting options for printf. I encountered the following flag to put after the '%#' symbol:
The value should be converted to an "alternate form". For o conversions, the first character of the output string is made zero (by prefixing a 0 if it was not zero already). For x and X conversions, a nonzero result has the string "0x" (or "0X" for X conversions) prepended to it. For a, A, e, E, f, F, g, and G conversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows). For g and G conversions, trailing zeros are not removed from the result as they would otherwise be. For other conversions, the result is undefined.
It seems that '%#' flag is for a kind of type conversion for the printf statement. But I am not sure. Does anyone knows what kind of conversion of actual usage this %# flag has in the printf function in C? I can see any change or conversion for the character "A", which is the one I am using for the flag %# in the last print statement.
This is my code:
#include <math.h>
int main(int argc, char *argv[])
{
int age = 32; // age and height not initialized
int height = 182;
printf("I am %d cm tall.\n", age);
printf("I am %d years old.\n", height);
printf("I wanna go to \"Panama\"\n"); // scaping double quotes
printf("I am %2$d tall and %1$d years old\n", age, height); // how to use positional arguments in printf statement
// how to use positional arguments in printf statement
printf("I am using the number pi: %'.2f\n", 3.1415939);
// Testing the %# formatting
printf("Testing for A: %# \n", 'A');
return 0;
}
The output I receive:
I am 32 cm tall.
I am 182 years old.
I wanna go to "Panama"
I am 182 tall and 32 years old
I am using the number pi: 3.14
Testing for A: %#
Solution 1:[1]
You are providing a legal # flag, but you do not specify any legal conversion character (idouxXsc etc...). In that case, the behavior of printf is undefined.
Here a few (untested) examples:
printf("%#x\n", 17);
printf("%#X\n", 17);
printf("%#f\n", 1.42);
printf("%#A\n", 1.42);
Reference:
- See the printf manual for reference.
man 3 printfchecking themanon your system can help you to understand behaviors not defined by the C standard.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sky Voyager |
