Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one use %8.8 over %08 in a printf format string?

Just came across some (very) legacy code (originally written as C but now compiled as C++ too) and a use of the width specifier to zero pad a string

void main()
{
    unsigned long val = 2413;
    printf("V1: %08lu \n", val);
    printf("V2: %8.8lu \n", val);
}

The results are identical

V1: 00002413
V2: 00002413

So why would one use V2? Was it some legacy aspect of the std lib from the days of yore?

Compiler details : Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25019 for x86

like image 321
Preet Sangha Avatar asked Jun 14 '17 22:06

Preet Sangha


People also ask

Why do we need %s in printf?

%s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char ); the type of the corresponding argument must be char * . %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int .

What format is used to print a string with the printf function?

C++ printf is a formatting function that is used to print a string to stdout. The basic idea to call printf in C++ is to provide a string of characters that need to be printed as it is in the program. The printf in C++ also contains a format specifier that is replaced by the actual value during execution.

What does %8s mean in C?

printf("%8s", "abc") will print abc , including 5 leading spaces: 8 is the "field width". Think of a table of data with column widths so that data in the same column is vertically aligned. The data is by default right-aligned, suitable for numbers.

What does %% mean in printf?

As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.


Video Answer


1 Answers

For unsigned integer types there's no difference. For negative values of signed integer types you will see different output

long val = -2413;
printf("V1: %08ld\n", val);
printf("V2: %8.8ld\n", val);

V1: -0002413
V2: -00002413

The .8 part of %8.8ld specifies the minimum number of digits to appear. And the - sign is not considered a digit. For this reason, the second version is required to always print 8 digits. If the value is negative, the - sign will have no choice but to become the 9th character printed, thus violating the requested field width of 8.

The %08ld version has no requirement to print at least 8 digits, which is why the - sign occupies one character inside the field width of 8 and only 7 digits are printed.

http://coliru.stacked-crooked.com/a/fc9022cc0ef3e097

like image 65
AnT Avatar answered Oct 13 '22 11:10

AnT