C Assignment Operator
In C, the Assignment =
operator is used to assign a value to a variable. It stores the right-hand side (RHS) value into the left-hand side (LHS) variable.
The Assignment Operator can also be used in combination with arithmetic and bitwise operators to perform compound assignments.
Syntax of the Assignment Operator
The syntax to use the Assignment Operator is:
variable = value;
Explanation:
variable
: The left-hand operand that stores the assigned value.=
: The assignment operator, which assigns the RHS value to the LHS variable.value
: The right-hand operand that provides the value to be assigned.
Examples of the Assignment Operator
1. Assigning a Value to a Variable
In this example, we will assign an integer value to a variable using the Assignment Operator and print the result.
main.c
#include <stdio.h>
int main() {
int num;
num = 10; // Assigning value
printf("The value of num is: %d\n", num);
return 0;
}
Explanation:
- We declare an integer variable
num
. - The statement
num = 10;
assigns the value 10 tonum
. - We print the value of
num
usingprintf()
.
Output:
The value of num is: 10
2. Chained Assignment
In this example, we will use chained assignment to assign a single value to multiple variables in a single statement.
main.c
#include <stdio.h>
int main() {
int a, b, c;
a = b = c = 20; // Chained assignment
printf("a = %d, b = %d, c = %d\n", a, b, c);
return 0;
}
Explanation:
- We declare three integer variables:
a
,b
, andc
. - The statement
a = b = c = 20;
assigns the value 20 to all three variables. - Since assignment returns the assigned value,
c = 20
assigns 20 toc
, thenb = c
assigns 20 tob
, and finally,a = b
assigns 20 toa
. - We print the values of
a
,b
, andc
usingprintf()
.
Output:
a = 20, b = 20, c = 20
3. Using Assignment with Arithmetic Operations
In this example, we will use the Assignment Operator with arithmetic operations to modify a variable’s value.
main.c
#include <stdio.h>
int main() {
int x = 5;
x = x + 10; // Arithmetic assignment
printf("The new value of x is: %d\n", x);
return 0;
}
Explanation:
- We declare an integer variable
x
and initialize it to 5. - The statement
x = x + 10;
increasesx
by 10 and stores the result back inx
. - We print the updated value of
x
usingprintf()
.
Output:
The new value of x is: 15
Conclusion
In this tutorial, we covered the Assignment Operator =
in C. The important points to remember are:
- The Assignment Operator is used to assign values to variables.
- It can be used for simple assignments, chained assignments, and arithmetic operations.
- The Assignment Operator returns the assigned value, allowing assignment chaining.