Expressions
Expressions Vs Statements
// Statements
int total_marks = pyhsics + chem + math; // statements
x = y = z;
// Expressions
int x = 10; // 10 is a expression
int y = 20, z = 30;
x = y = z + 10;
- Any variable name (x, y, z, β¦), constant, or literal is an expression.
- One or more expressions combined by an operator constitute an expression, e.g., x + y or x * y + z
In C++, assignment is also an expression, e.g., x = y + z. As a consequence, it can be used within another assignment: x2 = x = y + z. Assignments are evaluated from right to left.
Statements
Any of the expressions above followed by a semicolon is a statement.
The variable and constant declarations we have seen before are also statements. As the initial value of a variable or constant, we can use any expression.
A single semicolon is an empty statement, and we can thus put as many semicolons after an expression as we want.
int marks = 10 // statement
5 + 3 // expression
5 + 3; // statement
int z = 5 + 3; // statement
int total = marks; // statement
// Control Statements
if (...){
}
Operators
Arithmetic Operators
Relational Operators
A relational operator is used to check the relationship between two operands.
Operator | Function |
---|---|
== | isEqual to |
!= | Not Equal to |
> | Greater than |
< | Lesser than |
>= | Greater than or Equal to |
β | Lesser than or Equal to |
Logical Operators
Logical operators are used to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0.
Operator | Function |
---|---|
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Bitwise Operators
In C++, bitwise operators are used to perform operations on individual bits. They can only be used alongside char
and int
data types.
Operator | Function |
---|---|
& | Binary AND |
| | Binary OR |
^ | Binary XOR (Exclusive OR) |
~ | Binary one compliment (Flip all bits of a number) |
<< | Left Shift |
>> | Right Shift |
Assignment Operators
Also known as compound assignment operators (combine binary operator with assignment operator).
Operator | Function |
---|---|
= | Assignment |
+= | Compound Addition |
-= | Compound Subtraction |
*= | Compound Multiplication |
/= | Compound Division |
%= | Compound Modulo |
Misc Operators
Hereβs a list of some other common operators available in C++.
Operator | Function |
---|---|
sizeof | returns size of datatype |
?: | Ternary operator |
& | Address of operator |
. | Dot operator |
* | Dereference operator |
β | Access members of objects |
Increment Decrement
Arithmetic operators are used to perform arithmetic operations on variables and data.
Operator | Function |
---|---|
++ | Increment |
β | Decrement |
int a = 10;
a++; // postincrement
++a; // preincrement
a--; // postdecrement
--a; // predecrement
Associativity & Precedence
- Pending