Before studying the other C operators, it is important to understand that
processors can only perform operations on variables of the same type and size.
When the types are different, the compiler will
convert them (in a more or less judicious way) so that in the end, the calculation can
be done with two operands of the same type. For example: two short
or two double
.
For the same reason, the result of an operation is of the same type as the operands. For example:
This mechanism can have important consequences, let's analyze the two following examples.
Consider the following example:
float a=7, b=2;
printf ("7 / 2 = %f\n", a/b );
The operands a
and b
are of float type, the result of the division will be
a float, hence the format code %f
in the printf
. Here, no worries,
the result of 7 divided by 2 is 3.5.
Consider now the following example:
int a=7, b=2;
printf ("7 / 2 = %d\n", a/b );
The operands a
and b
are of type integer, the result of the division will
also be an integer, hence the format code %d
in the printf
. But beware,
an integer cannot contain a decimal number, the result will be truncated to the
the lower integer:
7 / 2 = 3
If the two operands are of different types, the compiler will perform an automatic type conversion. Needless to say, it is better to avoid letting the compiler choose the type of the result. We will see later that it is possible to perform type casting i.e. convert them temporarily to another type.
Write a program that declares 3 variables a
, b
and x
of type float
.
a
and b
to 5 and 2 respectivelya
by b
before putting the result in x
.x
.#include <stdio.h>
int main(void) {
// Declare x, a=5 and b=2 (type float)
// COMPLETE HERE
// Divide a by b => x
// COMPLETE HERE
// Display x
printf ("x = %f\n", x);
return 0;
}
Write a program that declares 3 variables a
, b
and x
of type int
.
a
and b
to 5 and 2 respectivelya
by b
before putting the result in x
.x
.#include <stdio.h>
int main(void) {
// Declare x, a=5 and b=2 (type int)
// COMPLETE HERE
// Divide a by b => x
// COMPLETE HERE
// Display x
printf ("x = %d\n", x);
return 0;
}
The processors can perform an operation on ...
What will be the value contained in the variable x
?
float x = 15 / 2;
What will be the value contained in the variable x
?
float x = 15. / 2.;
If the two operands are of different types, what will happen?
When the compiler automatically converts operands of different types ...