Basic Assignment Operator (=
) in C++
The assignment operator (=
) in C++ is one of the most fundamental operators. It is used to assign the value of the right-hand side expression to the left-hand side variable.
Purpose
- Stores a value in a variable.
- Can be used with literals, variables, or expressions.
- Enables initialization and value updates throughout the program.
Syntax
variable = value;
variable
: A declared identifier (must be declared before assignment).value
: A literal, expression, or another variable.
Example 1: Basic Integer Assignment
assignment_int.cpp
int a;
a = 5;
std::cout << a; // Output: 5
Explanation:
- Variable
a
is assigned the value5
using=
. - That value is stored and printed.
Example 2: Initialization at Declaration
assignment_declaration.cpp
int age = 21;
Explanation:
- This is known as inline initialization—declaring and assigning in a single step.
Example 3: Using Expressions
assignment_expression.cpp
int x = 10;
int y = 5;
int result = x + y; // result = 15
Explanation:
- The result of
x + y
is evaluated to15
and assigned toresult
.
Example 4: Assignment with Different Data Types
Float Assignment
assignment_float.cpp
float pi = 3.14f;
Character Assignment
assignment_char.cpp
char letter = 'C';
Boolean Assignment
assignment_bool.cpp
bool isOnline = true;
Example 5: Updating a Variable
assignment_update.cpp
int count = 1;
count = count + 1;
std::cout << count; // Output: 2
Explanation:
count + 1
is evaluated first → 2 is assigned tocount
.
Example 6: Chain Assignment
assignment_chain.cpp
int x, y, z;
x = y = z = 100;
Explanation:
- Values are assigned right-to-left.
- First,
z = 100
, theny = z
, and finallyx = y
.
Important Notes
-
The assignment operator
=
is not a comparison.x = 5
assigns.x == 5
checks equality.
Practice Exercises
- Declare a variable
radius
and assign it7.5
. - Assign a character
'A'
to a variable and print it. - Assign the sum of two integers into a third variable.
- Use chain assignment to assign
50
toa
,b
, andc
.
Common Mistakes
Mistake | Explanation |
---|---|
int x; x + 5; | The result is unused; assignment is missing. |
x == 10; | This checks equality instead of assigning. |
Summary
- The
=
operator assigns the right-hand value to the left-hand variable. - Supports all primitive types (
int
,float
,char
,bool
, etc.). - Enables chaining and inline initialization.
- Critical for program logic, variable updates, and calculations.