I have a code which intends to print some white-spaces after a string (to erase what could eventually be here, since I'm moving 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 );
Which I thought would produce "hello world", but no, it produces " hello world" (note that in my real code, the spaces are printed after the string, since the goal is to erase, not to indent, I'm simply doing this here to have working sample).
So, is this behavior intended? Since some_length is 0, one could reasonably hope to print nothing, right? Is this an undefined behavior, or could it be a but in the standard lib (I doubt it, but...)?
The * modifier for printf is used to specify a variable minimum width for the length of the next piece of output produced, rather than a fixed width for the length of the next piece of output produced. As a result, if you use * and provide a 0 as the numeric value of the length, it will have no effect because it says "print a space character, and never print fewer than zero characters."
I think you're forgetting the meaning of the %*. If you look it up, it's telling the compiler "I want to print at least this many widths. So, if you put zero, it's as if nothing happened, because it can obviously print 1 character width.
If say you change the number to a 5, it will pad it with 5 spaces, because there need to be at least 5 widths printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With