Assignment and Ternary Operators in C++ Tutorial

9/12/2025
All Articles

Assignment Ternary Operars in C++ cplus

Assignment and Ternary Operators in C++ Tutorial

Assignment and Ternary Operators in C++ Tutorial

Here’s a clear definition for Assignment and Ternary Operators in C++ Tutorial that you can use in your article or tutorial:

 

Assignment Operators

Assignment operators are used to assign values to variables. The basic assignment operator is =, and compound assignment operators combine an operation with assignment.

Operator Description Example Equivalent To
= Assign value a = 5
+= Add and assign a += 3 a = a + 3
-= Subtract and assign a -= 3 a = a - 3
*= Multiply and assign a *= 3 a = a * 3
/= Divide and assign a /= 3 a = a / 3
%= Modulus and assign a %= 3 a = a % 3
<<= Left shift and assign a <<= 1 a = a << 1
>>= Right shift and assign a >>= 1 a = a >> 1
&= Bitwise AND and assign a &= 3 a = a & 3
` =` Bitwise OR and assign `a
^= Bitwise XOR and assign a ^= 3 a = a ^ 3

Example:

#include <iostream>
using namespace std;

int main() {
    int a = 10;
    a += 5;
    a *= 2;
    cout << "Value of a: " << a << endl; // 30
    return 0;
}

Output:

Value of a: 30

Ternary (Conditional) Operator ?:

  • A shorthand for if-else statements.

  • Syntax: condition ? expression1 : expression2;

  • If condition is true, expression1 is executed, otherwise expression2 is executed.

Example:

#include <iostream>
using namespace std;

int main() {
    int age = 20;
    string result = (age >= 18) ? "Adult" : "Minor";
    cout << result << endl; // Adult
    return 0;
}

Output:

Adult

Summary

  • Assignment operators assign values and can combine operations with assignment.

  • Ternary operator provides a concise way to make conditional decisions.

  • These operators help write clean and efficient code.

Article