Expressions in C++
An expression in C++ is a
combination of:
- Operands → variables, constants,
literals
- Operators → +, -, *, /, ==, &&,
etc.
An expression produces a value.
Example:
a + b // arithmetic expression
x > 10 // relational expression
i++ // increment expression
flag && x // logical expression
Types of
Expressions in C++
1 Arithmetic
Expressions
Used for numeric calculations.
Operators:
+ - * / %
Example:
int a = 10, b = 3;
int c = a + b * 2; // result = 16
Key Point:
Operator precedence affects the result
* , / , % have higher precedence than + , -.
2 Relational
Expressions
Used to compare two values (returns
true/false).
Operators:
== != > < >= <=
Example:
int x = 10;
bool result = (x >= 10); // true
3 Logical
Expressions
Used for decision-making.
Operators:
&& || !
Example:
int age = 20;
bool ok = (age >= 18 &&
age <= 40); // true
4 Assignment
Expressions
Stores a value in a variable.
Operators:
= += -= *= /= %=
Example:
int x = 5;
x += 3; // x = x + 3 = 8
5 Increment &
Decrement Expressions
++ → increase by 1
-- → decrease by 1
Two Types:
- Pre-increment: ++x
- Post-increment: x++
|
Expression |
Meaning |
Example |
|
++x |
increments first, then uses value |
y = ++x; |
|
x++ |
uses value first, then increments |
y = x++; |
6 Conditional
Expression (Ternary Operator)
Short form of if-else.
Syntax:
condition? expression1 :
expression2
Example:
int marks = 70;
string result = (marks >= 40) ?
"Pass" : "Fail";
7 Bitwise
Expressions
Works at bit level.
& | ^ ~ << >>
Example:
int x = 5 & 3; // 0101 & 0011 = 0001 = 1
8 Pointer
Expressions
Used with memory addresses.
Example:
int a = 10;
int *ptr = &a;
cout << *ptr; // value at address
Operator
Precedence
From highest to lowest:
- ()
- ++,
-- (prefix)
- *,
/, %
- +,
-
- <,
<=, >, >=
- ==,
!=
- &&
- ||
- =,
+=, -= ...
0 Comments