Printf: cannot print less than 1 character with% * c

I have code that intends to print some spaces after a line (to erase what might end up being here as I move the cursor).

So, I used something like this:

int some_length = 0;
char some_string[]="hello world";
printf( "%*c%s\n", some_length, ' ', some_string );

I thought it would create a “hello world”, but no, it creates a “hello world” (note that in my real code spaces are printed after the line, since the goal is to erase, not indent, I just do it is here to have a working sample).

So, is this behavior intended? Since some_length is 0, you can hope you don’t print anything, right? Is this behavior undefined, or can it be, but in the standard library (I doubt it, but ...)?

+4
source share
2 answers

The * modifier for printf is used to specify a variable minimum width for the length of the next produced work, rather than a fixed width for the length of the next produced work. As a result, if you use * and provide 0 as a numeric value for the length, this will have no effect, because it says "print whitespace and never print less than zero."

+6
source

I think you forget the meaning of% *. If you look at it, it tells the compiler, “I want to print at least this width. So, if you put zero, it is as if nothing happened, because it can obviously print 1 character width.

, 5, 5 , 5 .

+1

All Articles