C++ Tutorial menu

C++ Operators

Operators let you calculate, compare and combine values in C++.

Arithmetic Operators

OperatorMeaningExampleResult
+Add9 + 211
-Subtract9 - 27
*Multiply9 * 218
/Divide9 / 24
%Remainder9 % 21
++Increase by 1x++
--Decrease by 1x--

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int seconds = 200;
  cout << seconds / 60 << " minutes and " << seconds % 60 << " seconds\n";
  cout << 9 / 2.0 << "\n";
  return 0;
}
Output
3 minutes and 20 seconds
4.5

If both numbers are integers, / gives an integer. Write one as a decimal (2.0) or use static_cast<double> when you need the exact answer.

Prefix and Postfix

x++ uses the value first and then adds 1. ++x adds 1 first and then uses the value:

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int a = 5;
  int b = a++;   // b gets 5, then a becomes 6
  int c = ++a;   // a becomes 7, then c gets 7
  cout << a << " " << b << " " << c << "\n";
  return 0;
}
Output
7 5 7

Assignment Operators

OperatorSame as
x += 4x = x + 4
x -= 4x = x - 4
x *= 4x = x * 4
x /= 4x = x / 4
x %= 4x = x % 4

Comparison Operators

Each comparison gives a bool result:

OperatorMeaning
==Equal
!=Not equal
>, <Greater, less
>=, <=Greater or equal, less or equal

Logical Operators

  • && and: both must be true
  • || or: at least one must be true
  • ! not: reverses true and false

Example

cpp
#include <iostream>
using namespace std;

int main() {
  int marks = 72;
  int attendance = 85;
  bool eligible = marks >= 50 && attendance >= 75;

  cout << boolalpha;
  cout << "Eligible for exam: " << eligible << "\n";
  cout << "Needs help: " << (marks < 40 || attendance < 60) << "\n";
  return 0;
}
Output
Eligible for exam: true
Needs help: false

Order of Operations

*, / and % are done before + and -. Comparisons come after maths, and && comes before ||. When in doubt, use brackets:

Example

cpp
int x = 10 + 2 * 5;     // 20
int y = (10 + 2) * 5;   // 60

Exercise

Exercise

What is printed by: int n = 3; cout << n++; ?

Learn C++ with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp