Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between %d and %*d in c language?

Tags:

c

integer

What is %*d ? I know that %d is used for integers, so I think %*d also must related to integer only? What is the purpose of it? What does it do?

int a=10,b=20;
printf("\n%d%d",a,b);
printf("\n%*d%*d",a,b);

Result is

10 20 
1775 1775 
like image 230
Parag Avatar asked Mar 30 '12 04:03

Parag


2 Answers

The %*d in a printf allows you to use a variable to control the field width, along the lines of:

int wid = 4;
printf ("%*d\n", wid, 42);

which will give you:

..42

(with each of those . characters being a space). The * consumes one argument wid and the d consumes the 42.

The form you have, like:

printf ("%*d %*d\n", a, b);

is undefined behaviour as per the standard, since you should be providing four arguments after the format string, not two (and good compilers like gcc will tell you about this if you bump up the warning level). From C11 7.20.6 Formatted input/output functions:

If there are insufficient arguments for the format, the behavior is undefined.

It should be something like:

printf ("%*d %*d\n", 4, a, 4, b);

And the reason you're getting the weird output is due to that undefined behaviour. This excellent answer shows you the sort of things that can go wrong (and why) when you don't follow the rules, especially pertaining to this situation.

Now I wouldn't expect this to be a misalignment issue since you're using int for all data types but, as with all undefined behaviour, anything can happen.

like image 121
paxdiablo Avatar answered Nov 09 '22 18:11

paxdiablo


When used with scanf() functions, it means that an integer is parsed, but the result is not stored anywhere.

When used with printf() functions, it means the width argument is specified by the next format argument.

like image 38
Jonathan Wood Avatar answered Nov 09 '22 18:11

Jonathan Wood