I'm starting a youtube course on C.
And they show that to print the values of the variables it is necessary to use this operator %
.
example:
int suma, a, b;
a=2;
b=3;
suma=a+b;
printf("El valor de la suma es %i", suma);
In case of integer %i
, float %f
and char%c
I would like to know what other uses this operator has and what attributes it has depending on the value, because I saw that I could delimit the displayed decimals using %.1f
or%.2f
In the context you define the
%
is not an operator but a format specifier .In C, the format specifiers are what tell variadic functions what type of argument to work with.
In the simplest case:
Tells the compiler to optimize the function call
printf
for an argument of typechar *
.The most common format specifiers can be:
*: These specifiers may be out of standard.
Outside of this context, it is a modulo operator and is used to obtain the remainder of a division.
EDIT:
Additionally, as I mentioned in the beginning, it is a format specifier, they can also be used to fill spaces with zeros or as you wish:
This will result in:
Or also:
The latter limits printing to the first 3 places after the decimal point in a
float
.EDIT 2:
I felt that some information was missing from this answer, which is now present in this edition, and that is that the format specifiers have some magic inside them.
Let's organize this by types:
char *
o "C-String" : Its specifier is%s
, but what happens if we do:%.2s
?Suppose we have the following string:
"Hola Mundo"
and we do:The answer is: It is limited to printing only 3 characters of the current parameter; in the same way it can be used to space the strings:
What if we mix them?
As you can see, all formatting of a string is possible in C.
The character
*
inside a format specifier must include an additional parameter in the function call to specify its value, as in the examples mentioned above.Below is a table with the possible types of format that can be given to a parameter, see last reference (Wikipedia):
The format is applied practically the same for all types, but you still have to be careful.
Some references:
printf
(C++Reference)printf(const char fmt, ...)
printf
It is also used for the Modulus operator, which is nothing more than the remainder of a division. For example, here is a small piece of C code that tells whether a number is odd or even:
This should display "The number is even", because if you divide an even number by 2, the remainder will always be 0. I hope it has helped you.