C++ operators are symbols or keywords used to perform operations on variables and values. These operators are used to manipulate data and variables in different ways.
1. Arithmetic Operators
These operators are used to perform basic mathematical operations like addition, subtraction, etc.
Example:
int a = 20;
int b = 5;
cout << a + b << endl; // Output: 25 (Addition)
cout << a - b << endl; // Output: 15 (Subtraction)
cout << a * b << endl; // Output: 100 (Multiplication)
cout << a / b << endl; // Output: 4 (Division)
cout << a % b << endl; // Output: 0 (Remainder)
2. Relational (Comparison) Operators
These operators are used to compare two values and return a boolean result (true or false).
Example:
int a = 20;
int b = 5;
cout << (a == b) << endl; // Output: false
cout << (a != b) << endl; // Output: true
cout << (a > b) << endl; // Output: true
cout << (a < b) << endl; // Output: false
cout << (a >= b) << endl; // Output: true
cout << (a <= b) << endl; // Output: false
3. Logical Operators
These operators are used to perform logical operations, commonly in conditional statements.
Example:
bool a = true;
bool b = false;
cout << (a && b) << endl; // Output: False (Both must be true)
cout << (a || b) << endl; // Output: True (At least one is true)
cout << (!a) << endl; // Output: False (Reverses the value)
4. Assignment Operators
These are used to assign values to variables.
Example:
int a = 20;
a += 10; // a = a + 10 => num = 30
a -= 5; // a = a - 5 => a = 25
a *= 2; // a = a * 2 => a = 50
a /= 5; // a = a / 5 => a = 10
cout << (a) << endl; // Output: 10
5. Ternary Operator
This is a shorthand for an if-else statement.
Syntax:
condition ? expression_if_true : expression_if_false
Example:
int age = 19;
string result = (age >= 18) ? "Adult": "Not Adult";
cout << (result) << endl; // Output: Adult
6. Scope Resolution Operator (::)
It is used to define the scope of a function or variable.
std::cout << "Hello, World!"; // Access cout in std namespace
C++ Operators – Interview Questions
Q 1: What are operators?
Q 2: Types of operators in C++?
Q 3: What is == operator?
Q 4: Difference between = and ==?
Q 5: What is logical AND operator?
C++ Operators – Objective Questions (MCQs)
Q1. Which of the following is the correct arithmetic operator for addition in C++?
Q2. What will be the output of the following code?
int a = 10, b = 3;
cout << a / b;
Q3. Which of the following operators is used to compare two values in C++?
Q4. What is the result of the expression 10 % 3 in C++?
Q5. Which of the following is a logical AND operator in C++?