Operations on variables

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Operations on variables

Changing the value of a variable

Here, we set the value of a variable named 'age' to 24:

age = 24;

We can also set the value of a variable when we define it:

int age = 25;

We can define many variables of the same type at once:

int day = 3, month = 7, year = 1994;

Mathematical operations

Let us define two variables:

int var = 5, var2 = 7;

Addition

Let us add them together:

var + var2;

The instruction above does not change the value of neither of the variables... It simply produces a result.

If we want to do something with the result, we must 'catch' it. Here we assign the result to a new variable:

int var3 = var + var2;

It is possible to add an = sign after the + to execute the addition and assign the result to the variable at once.

So, instead of that:

var = var + var2;

We can write that:

var += var2;

Incrementing and decrementing

The following:

var++;

Is a shortcut of:

var += 1;

And this:

var--;

Is equivalent to:

var -= 1;

Those shortcuts exist because adding/subtracting one to/from a variable happens quite often.

Multiplication and division

Multiplication and division work the same way as addition, except that the symbols are, respectively, * and /.

We multiply 'var' by 'var2':

var * var2;

We divide 'var' by 0.5:

var / 0.5;

Modulo

The modulo operation is a bit trickier (Only because it is less known). Its symbol is % and its result is the remainder of an integer division... So, for example, 5 % 2 equals 1, because 5 can be fully divided by 2 only two times and then, the remainder is 1 (5 - (2 * 2)).

The variable 'var' modulo 7:

var % 7;

Operators and operands

The symbols used to execute operations on variables, like +, are called operators. The variable/value at the left of that symbol is called the left operand and the variable/value at the right is said to be the right operand.

Operations with variables of different types

When we execute operations on variables of different types, they are automatically converted:

int var1 = 50; unsigned var2 = var1;

Above, 'var2' equals 50, but as a value of type 'unsigned'.

However, be careful. In some cases, a conversion may cause data loss.

For example, when a value of floating-point type is converted to an integer type, it loses the digits after its decimal point:

int var = 5.1234;

Above, 'var' equals 5.

Data loss can also arise if a value is converted to a type that is not big enough to hold it:

char var = 99999999;

Or if a negative number is converted to an unsigned type:

unsigned var = -5;