CodeMIRAI
0 XP

Operators

3 min read 7 runnable examples Quiz included

Arithmetic

C++
#include <iostream>
using namespace std;

int main() {
    int a = 17, b = 5;
    cout << a + b << endl;      // 22
    cout << a - b << endl;      // 12
    cout << a * b << endl;      // 85
    cout << a / b << endl;      // 3: int / int drops the remainder
    cout << a % b << endl;      // 2: the remainder
    cout << 17.0 / 5 << endl;   // 3.4
    return 0;
}

Dividing two integers gives an integer, with the remainder thrown away, and % gives that remainder. Make either side a floating-point number to keep the decimals.

Compound assignment, ++ and --

C++
#include <iostream>
using namespace std;

int main() {
    int score = 10;
    score += 5;     // 15
    score -= 3;     // 12
    score *= 2;     // 24
    score /= 5;     // 4: integer division
    cout << "score = " << score << endl;

    int x = 5;
    int y = x++;    // y gets 5, then x becomes 6
    int z = ++x;    // x becomes 7, then z gets 7
    cout << x << " " << y << " " << z << endl;
    return 0;
}

x++ hands over the old value and then adds one; ++x adds one first. As in C, never use ++ on the same variable twice in one expression: the result is undefined.

Comparisons and logic

C++
#include <iostream>
using namespace std;

int main() {
    int age = 19;
    bool hasTicket = true;
    cout << (age >= 18) << endl;                  // 1
    cout << (age == 21) << endl;                  // 0
    cout << (age >= 18 && hasTicket) << endl;     // 1
    cout << (age < 13 || age > 65) << endl;       // 0
    cout << !hasTicket << endl;                   // 0
    return 0;
}

A comparison gives a bool, which cout prints as 1 or 0. To print true and false instead, send boolalpha to the stream first:

C++
cout << boolalpha << (age >= 18) << endl;    // true

&& and || stop early: if the left side already decides the answer, the right side isn't evaluated at all.

The << precedence trap

<< is also the left-shift operator, and it binds more tightly than comparisons and &&. Forget the brackets, and the expression means something else entirely:

C++
cout << a < b << endl;      // compile error: parsed as (cout << a) < (b << endl)
cout << (a < b) << endl;    // what you meant

Put brackets around any comparison, logical or conditional expression you print.

Converting types

C++
#include <iostream>
using namespace std;

int main() {
    int total = 7, count = 2;
    double wrong = total / count;               // 3: divided as integers first
    double right = (double) total / count;      // 3.5: converted first
    cout << wrong << " " << right << endl;

    double price = 9.99;
    int whole = (int) price;                    // 9: the fraction is cut off
    cout << whole << endl;
    return 0;
}

The bracketed casts above are C style. Modern C++ prefers static_cast, which says exactly what kind of conversion you mean and is easy to search for:

C++
double right = static_cast<double>(total) / count;    // 3.5
int whole = static_cast<int>(price);                  // 9

Precedence

C++
#include <iostream>
using namespace std;

int main() {
    cout << 2 + 3 * 4 << endl;        // 14
    cout << (2 + 3) * 4 << endl;      // 20
    cout << 20 - 10 - 5 << endl;      // 5: left to right
    cout << 7 % 3 * 2 << endl;        // 2: % and * share a level, left to right
    return 0;
}

From high to low: ++ and --, then * / %, then + -, then << >>, comparisons, == !=, &&, ||, the conditional ?:, and finally assignment. When in doubt, add brackets.

Bitwise operators

C++
#include <iostream>
using namespace std;

int main() {
    int a = 12;    // binary 1100
    int b = 10;    // binary 1010
    cout << (a & b) << endl;      // 8    AND
    cout << (a | b) << endl;      // 14   OR
    cout << (a ^ b) << endl;      // 6    exclusive OR
    cout << (a << 2) << endl;     // 48   shift left: times 4
    cout << (a >> 1) << endl;     // 6    shift right: divided by 2
    return 0;
}

The brackets are essential here: without them, cout << a << 2 would print 12 and then 2.

sizeof and big numbers

C++
#include <iostream>
using namespace std;

int main() {
    cout << "int: " << sizeof(int) << " bytes" << endl;
    cout << "double: " << sizeof(double) << " bytes" << endl;
    cout << "long long: " << sizeof(long long) << " bytes" << endl;

    long long views = 3000000000LL;
    cout << views * 2 << endl;    // 6000000000: too big for an int
    return 0;
}

An int holds values up to about 2.1 billion. Going past that with a signed integer is undefined behaviour in C++: the program may give any result at all. Use long long (at least 64 bits) for big values, written with an LL suffix.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.