Antonin Hérault
Antonin Hérault

Antonin Hérault

Arithmetic and boolean operations (5)

Antonin Hérault's photo
Antonin Hérault
·Jul 12, 2022·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Arithmetic operators
  • Boolean operators
  • Arithmetic operators for variables

It's time to discover how operations work in C.

Arithmetic operators

OperatorsJob
+Adds two values
-Subtracts two values
*Multiplies two values
/Divides two values
%Remainder of a division between two values

Examples

double mul(float a, float b) {
    return a * b;
}
#include <math.h>

double pythagore(float a, float b) {
    return sqrt(a * a + b * b);
}
#include <stdio.h>
#include <assert.h>

int main(void) {
    assert((float) 5 / 2 == 2.5);
    assert(5 % 2 == 1);
    return 0;
}

Boolean operators

OperatorsJob
==Are both values equal ?
!=Are both values different ?
<Is the first value less than the second one ?
>Is the first value greater than the second one ?
>=Is the first value less or equal than the second one ?
<=Is the first value greater than the second one ?
!Reverse a boolean expression

Examples

#include <math.h>

double pythagore(float a, float b) {
    return sqrt(a * a + b * b);
}

int main(void) {
    assert(pythagore(3, 4) == 5);
    return 0;
}
#include <assert.h>

int main(void) {
    assert(5 >= 2);
    assert(23 >= 23);
    assert(1 <= 10);
    assert(9 == 9);
    assert(5 != 2);
    assert(!(5 <= 2));

    return 0;
}

Arithmetic operators for variables

OperatorsJob (when it assigns it does to the variable)
+=Adds a value to the variable
-=Subtracts a value from the variable
*=Multiplies the variable's value by a value and assign the result
/=Divides the variable's value by a value and assign the result
%=Assigns the remainder of a division between the variable's value and a value
++Increments the variable by one
--Decrements the variable by one
a = a + 2;
a += 2;

Both expressions are the same

Examples

#include <assert.h>

int main(void) {
    int a = 10;
    a += 1;
    assert(a == 11);

    a++;
    assert(a == 12);
    ++a;
    assert(a == 13);

    --a;
    assert(a == 12);

    return 0;
}
#include <assert.h>

int main(void) {
    int a = 10;
    a *= 2;
    assert(a == 20);

    return 0;
}

Difference between ++x and x++

The only difference between the prefix and the postfix notation is the returned value of the expression.

With the postfix notation, the variable's value is returned then the variable is incremented.

With the prefix notation, the variable is incremented then the the varibale's value is returned

int postfix = 5;
assert(postfix++ == 5);
assert(postfix == 6);

int prefix = 5;
assert(++prefix == 6);
assert(prefix == 6);