Assignment Statements in Arduino Sketches
An assignment stores the result of an operation (or set of operations) in a variable. Assignments in Arduino sketches follow the syntax rules of the C language..fs
Table of contents
- Assignments with numerical variables
- Assignment with function output
- Logical operations and assignments
Assignments with numerical variables
Basic ideas
Assignments with mixed types
Extending the preceding example of mathematical operations, a program could contain these two assignments.
c = a + b
d = 2.0*sqrt(c)
The results follow our common sense. The value stored in d
is the sum of a
and b
. The value store in d
is the result of multiplying the square root of the number stored in c
by 2.0. However, even these straightforward assignments can have subtle effects. For example, the type of variable matters.
Recall the previous example of variable declarations and combine them with the assignment operations.
float a, b, d;
int c;
c = a + b
d = 2.0*sqrt(c)
The preceding set of statements have correct C/C++ syntax and would be valid parts of an Arduino sketch. This example is missing a key ingredient, the statements that provide values for
a
andb
. We can continue without giving specific values stored ina
andb
, but if it helps, you can insert these linesa = 1.2345; b = -0.00023;
Realize, however, that thinking about the assignments
c = a + b
andd = 2.0*sqrt(c)
need to be generalized to any values that are stored ina
andb
.
Given that a
and b
are float
type and c
is an int
type, the result of c = a + b
is that only an integer can be stored in c
. When a + b
is evaluated by the Arduino microcontroller, the result is a temporary floating point value. The assignment c = a + b
truncates the result of a + b
and stores the resulting integer in c
.
Numerical variables like a
, b
and c
can be integers or floating point types. The type of the variable determines what can be stored in that variable. Suppose that c
is an integer type, which means that any value stored in c
cannot have an fractional component. In contrast to the integer type, a floating point type can store fractional values. Now, if a
and b
are floating point variables and c
is an integer, then the result of the assignment is that the true sum of a
and b
will be truncated before it is stored in c
.