Question

I came up with a code

#include <stdio.h>

int main()
{ 
   int i = 1427;
   double d = 1427.0;

   printf("%#o\n", i);
   printf("%#X\n", i);
   printf("\n%g\n", d);
   printf("%#g\n", d);
   return 0;
}

which is giving the output:

02623
0X593

1427
1427.00

First I thought # is used for prefixing 0 to the output but I was wrong because of its strange behavior in last output in which it is printing zeroes after decimal.
Could someone explain what this #is and what it is doing here?

Was it helpful?

Solution

The # flag has a different behavior, depending on context.

If it is used with the o, x, or X specifiers, the value is preceded with 0, 0x, or 0X respectively.

If it is used with a/A, e/E, f/F, or G, the value always ends with a decimal point.

This behavior is quite well documented multiple places on the web. Searching for "printf" and possibly "format specifiers" will generally turn up lots of good links. Here are a few to whet your appetite:

OTHER TIPS

From the POSIX man pages man 3p printf:

#: Specifies that the value is to be converted to an alternative form. For o conversion, it increases the precision (if necessary) to force the first digit of the result to be zero. For x or X conversion specifiers, a non-zero result shall have 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g, and G conversion specifiers, the result shall always contain a radix character, even if no digits follow the radix charac‐ ter. Without this flag, a radix character appears in the result of these conversions only if a digit follows it. For g and G conversion specifiers, trailing zeros shall not be removed from the result as they normally are. For other conversion specifiers, the behavior is undefined.

Putting it simple: it prints the alternative format, whatever it is. For hex. values, it is prefixing 0x, for octal 0, and for floating points, it forces some decimal rules...

I think that if you read about C's printf function here, you'll be able to further understand things such as "#", among others.

Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.

Exerpt from wikipedia:

# Alternate form. For 'g' and 'G', trailing zeros are not removed. For 'f', 'F', 'e', 'E', 'g', 'G', the output always contains a decimal point. For 'o', 'x', and 'X', a 0, 0x, and 0X, respectively, is prepended to non-zero numbers.

%#o (Octal) 0 prefix inserted.

%#x (Hex) 0x prefix added to non-zero values.

%#X (Hex) 0X prefix added to non-zero values.

%#g Always show the decimal point trailing zeros not removed.

Zeroes are bound to come after decimal because you are using %#g.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top