Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

%*s Format specifier C [closed]

Tags:

c

printf

scanf

printf("%d",printf("%*s%*s",6,"",6))

Results in the addition of the 2 numbers (6+6), does anyone have on such type of format specifiers

like image 411
Akash Avatar asked Jan 18 '23 07:01

Akash


2 Answers

Your example is malformed, there's a missing argument to the "nested" printf.

If you write it like this:

printf("%d",printf("%*s%*s",6,"",6, ""));

if becomes kind of ok. The * means that the precision field must be read from the next argument to printf. So in this case, the "nested" printf prints two strings of length at most 6.

Since printf returns the number of characters written, the inner printf returns 12, which the outer printf prints.

Quote from the relevant part of the man page:

The precision

An optional precision, in the form of a period ('.') followed by an optional decimal digit string. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just '.', or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F con‐ versions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

I'm not sure how portable this is, but what I'm sure of is that there are much better ways to add two numbers.

like image 92
Mat Avatar answered Jan 25 '23 12:01

Mat


A * as the width specifier indicates that the width is passed in as a parameter.

printf("%*s%*s", 6, "", 6, "");

is equivalent to:

printf("%6s%6s", "", "");

This would print out 12 spaces.

Since printf returns the number of characters printed, it will return 12.

The original code is missing the final "" parameter. If it works, it is purely by accident.

like image 23
Ferruccio Avatar answered Jan 25 '23 10:01

Ferruccio