Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf: can't print less than 1 character with %*c

Tags:

c

printf

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...)?

like image 933
user3459474 Avatar asked Mar 13 '23 19:03

user3459474


2 Answers

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."

like image 151
templatetypedef Avatar answered Apr 06 '23 01:04

templatetypedef


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.

like image 35
guptashark Avatar answered Apr 06 '23 00:04

guptashark