How many parameters are there in this printf () function?

I am very new to programming. Now I am studying C

. Have a look at this following piece of code -

printf("StudentId: %d CGPA: %f", id, cgpa); 
printf("Name: %s StudentId: %d CGPA: %f", name, id, cgpa);   

      

I know the function takes an argument. Therefore, I think the first and second methods printf()

only take two arguments -

1.the first argument is inside a double quote - or 2.and the second is outside the quote - or "StudentId: %d CGPA: %f"

"Name: %s StudentId: %d CGPA: %f"


id, cgpa

name, id, cgpa

Now my question is, am I right when I think methods prinf()

only take two arguments no matter how many variables (i.e. id, cgpa, name, or even department ) are placed after the double quotes?

Or If a method printf()

takes multiple arguments, then how is it handled in C?

+3


source to share


5 answers


No, you can't say that it printf

always takes 2 arguments. In your first case, it takes 3 arguments. In the second case, 4 arguments are required.



printf

is a variation function . It takes a variable number of arguments. In C, the functionality for such functions is provided through the header file stdarg.h

(or varargs.h

)
.

+4


source


Printf

can take as many arguments as possible.

On the man page you can see ...

at the end what var args means.



If you got 96 times %s

in your first argument, you have 97 arguments (first line + 96 replaced lines;))

+3


source


printf

can accept any number of inputs. This is what the prototype looks like printf

:

int printf ( const char * format, ... );

      

As you can see, ...

is an indicator of a variable number of arguments.

Example:

 printf("%i %d %f %c %s", int_var, int_var, float_var, char_var, string_var);

      

These are format specifiers:, %i, %d, %f, %c, %s

and they correspond to variables in order:int_var, int_var, float_var, char_var, string_var

+2


source


NO takes a variable number of arguments.

int printf(const char *format, ...)

takes a variable no arguments

format is a string that contains the text that will be written to standard output. It can optionally contain inline format tags, which are replaced with the values ​​specified in subsequent optional arguments and formatted as requested.

The printf function uses its first argument to determine how many arguments to follow, and what types they are. If you don't use enough arguments, or if they are of the wrong type, then printf will get confused, resulting in incorrect answers.

And the rest of the arguments are variables for the format tags that you specified in the first argument (as a string).

Please read here

+2


source


Take a look:

printf("StudentId: %d CGPA: %f", id, cgpa); //3 arguments 
printf("Name: %s StudentId: %d CGPA: %f", name, id, cgpa); // 4 arguments 

      

printf()

can take variable length arguments.

+1


source







All Articles