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?
source to share
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
) .
source to share
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
source to share
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
source to share