Assignment Operators In C | A Complete Guide With Detailed Examples
Operators are symbols or special characters that perform specific operations on one or more operands. They enable various computations and manipulation of data/ operands in C programs. These operands can be variables, constants, or expressions. It is important to understand the concept of various types of operators to utilize them effectively in writing efficient C code. In this article, we will focus on assignment operators in C.
Other types of operators include arithmetic, bitwise, logical, relational, ternary/ conditional, etc. Collectively, they enable complex computations, comparisons, and control flow within programs, allowing developers to manipulate data in a variety of ways.
What Are Assignment Operators In C?
In simple terms, assignment operators in C programming are used to assign values to variables. This includes assigning initial value as well as updating the value of a variable with a new value based on a certain operation or calculation. The most commonly used assignment operator is the equal-to operator (=), which assigns the right-hand side value to the variable on the left-hand side of the operator.
For example, the expression x = 5 assigns the value of 5 to the variable x.
Other assignment operators in C include addition assignment (+=), subtraction assignment (-=), multiplication assignment (*=), division assignment (/=), and modulus/ modulo assignment (%=). They are also referred to as compound assignment operators. As their name suggests, they are used to assign the resultant value of addition, subtraction, multiplication, division, and modulus operations (respectively) to the left-side variable/ operand.
For example, the equation x += 5 is equivalent to x = x + 5. It updates the value of x by adding 5 to its current value.
These assignment operators can be combined with other operators to perform more complex operations in a single statement. For example, x += y * 3 updates the value of x by adding three times the value of y to its current value.
Using basic assignment operators can help make code more concise and easier to read and improve performance by reducing the number of operations required. However, it is important to use them carefully and avoid unintended consequences, such as side effects or errors. We will discuss each of these assignment operators in detail ahead, but first let's look at the basic syntax for this.
Syntax For Assignment Operators In C:
variable_name operator expression;
Here,
- The variable_name refers to the name/ identifier of the variable to whom you are assigning (or updating) a value.
- The term operator refers to the respective assignment operator you are using.
- Expression is the right-hand operand, i.e., it refers to the value you assign to the variable.
Here are some examples of assignment operators and their syntax:
x = 5; // assigns the value of 5 to the variable x
y += 10; // adds 10 to the current value of y and updates y with the result
z *= 3; // multiplies the current value of z by 3 and updates z with the result
How Assignment Operators In C Work? Step-By-Step Explanation
Given below is a stepwise description of the working mechanism of assignment operators in C.
- Step 1 (The variable): The first step is to select the variable that we want to assign a value to. This variable can be of any data type, such as integer, float, or char.
- Step 2 (The operator): The second step is to select the assignment operator that we want to use. As mentioned, the most commonly used assignment operator is the simple assignment operator (=), to assign the value of the right side operand to the left side operand.
- Step 3 (The value or expression): The third step is to provide the value (or expression for calculating value) we want to assign to the variable. This value can be a constant or an expression that combines variables and constants using arithmetic or logical operators.
- Step 4 (The evaluation): After that, the compiler evaluates the expression on the right-hand side of the operator. This evaluation involves performing any necessary logical or arithmetic operations based on the precedence rules of the operators.
- Step 5 (The assignment): Finally, it assigns the evaluated value to the variable on the left-hand side of the assignment operator. If we are updating the value, this assignment replaces the previous value of the variable with the new value.
Let's look at a basic C program example illustrating both these approaches of using assignment operators.
Code Example:
Output:
The initial values of x and y are: 5, 10
The updated value of x is: 15
Explanation:
We begin the simple C program example by including the <stdio.h> header file for input/output operations.
- We then initiate the main() function, which is the entry point of the program's execution.
- Inside main(), we declare two integer variables, x and y, and assign the values of 5 to x and 10 to y. Then, we print these initial values to the console using the printf() function.
- Next, we use the addition assignment operator (as mentioned in the code comments) to add the initial value of y to the initial value of x and assign the result to x.
- The operation involves adding the value of y, which is 5, to the value of x, which is 10. The output is, hence, 15.
- Once again, we use the printf() function to display the updated value of x.
Types Of Assignment Operators In C
All the assignment operators in C programming language can be classified into two major types with subtypes. These types and the operators included in them are mentioned below-
Simple Assignment Operator In C (=)
There is only one assignment operator that falls into this category. This is the simplest assignment operator whose only purpose is to assign the value given on the right to the variable on the left. The basic assignment operator symbol is a single equals sign (=). It is the most commonly used assignment operator in C language. Below is an example of how to use this operator in simple assignment expressions.
Code Example:
Output:
The value of x is 5
Explanation:
In the simple C code example, we include the standard input-output header file, <stdio.h>, which contains the library functions for input and output operations in C programming.
- Inside main() funtion, we declare an integer variable named x and initialize it with the value 5 using the simple assignment operator.
- This step reserves a memory location to store an integer value and assigns the value 5 to x.
- Next, we use the printf() function to display the output with a descriptive string message (using formatted string).
- Here, we use the %d format specifier as a placeholder for the integer value and the newline escape sequence (\n) to shift the cursor to the next line afterwards.
- Lastly, the program successfully completes execution with the return 0 statement. It indicates the successful termination of the main() function and the program as a whole.
It will be easier to understand why we call this operator simple when you check out the other category, i.e., compound operators.
Compound Assignment Operators In C
The compound assignment operators are called as such because they combine a binary operation with the assignment operation. They perform a binary operation on the values of the variable and the value on the right-hand side and then assign the result to the variable on the left-hand side/ left operand.
There are five types of compound assignment operator in C:
- Subtraction Assignment Operator (-=)
- Addition Assignment Operator (+=)
- Multiplication Assignment Operator (=)
- Division Assignment Operator (/=)
- Modulus Assignment Operator (%=)
The advantage of using these operators is that they provide a shorthand notation for performing common operations such as addition, multiplication, division, etc.
Now that you have a broad idea of what compound assignment operators in C are, let's explore each type of assignment operator in detail.
Addition Assignment Operator In C (+=)
The addition assignment operator adds the value given on its right side to the current value of the variable on the left. It then assigns the resultant value back to the variable on the left.
In other words, it adds the initial value of the first variable to the initial value of a second variable and assigns it back to the first variable. Below is a C program example illustrating the use of this compound assignment operator.
Code Example:
Output:
The value of x is 8
Explanation:
In the C code example, we first include the essential header files.
- Inside the main() function, we declare an integer variable, x, and initialize it with the value 5 using the simple assignment operator.
- Next, we use the addition assignment operator (+=) to add a value 3 to x (variable on the left side) and assign the result back to it.
- Here, we add 3 to x's initial value and reassign it back. That is, x += 3 is equivalent to x = x + 3, which adds 3 to x's value and stores the result back into x.
- Then, we use the printf() function to display the output to the console, after which the program terminates with the return 0 statement.
Check out this amazing course to become the best version of the C programmer you can be.
Subtraction Assignment Operator In C (-=)
The subtraction assignment operator is used to subtract a given value, mentioned on the right side of the operator, from the initial value of the variable on the left (i.e., the left operand). It then assigns the result back to the original variable on the left. Alternatively, we can also subtract the value of a second variable from the initial variable.
Code Example:
Output:
The value of x is 7
Explanation:
In the example C program-
- Inside the main() function, we declare an integer variable x and assign the value 10 to it using the simple operator.
- We then use the subtraction assignment operator (-=) to subtract a value 3 from the initial value of x. The result is assigned back to x using this operator.
- Here, the expression x -= 3 is equivalent to x = x - 3, which means we subtract 3 from 5 (i.e., the value of x), and the value of x is updated with the result.
- After that, we use the printf() function to display the updated value of the variable x to the console.
Multiplication Assignment Operator In C (*=)
The multiplication assignment operator in C (*=) first multiplies a given value (on the right) with the initial/ current value of the variable on the left (left operand). Then, it assigns the result back to the variable on the left. Alternatively, it can also be used to multiply the initial value of a variable by the value of another variable in the program.
Code Example:
Output:
The value of x is 20
Explanation:
In the example C code-
- Inside the main() function, we declare an integer variable named x and initialize it with the value 5 using the simple assignment operator.
- Next, we use the multiplication assignment operator to multiply the initial value of x by 4 and then assign the result back to variable x.
- That is, the expression x *= 4 implies x = x * 4, which multiplies the value of x by 4 and stores the result back into x.
- Using the printf() function, we display the updated value of x and a string literal message.
Division Assignment Operator In C (/=)
The division assignment operator (/=) first divides the current/ initial value of the variable mentioned on its left side by the value given on its right. Then, the revised value/ result is assigned back to the variable on the left. Alternatively, we can also use this operator to divide the value of one variable by another variable and then update the value of one.
Let's take a look at an example that illustrates the use of this compound assignment operator in C code.
Code Example:
Output:
The value of x is 5
Explanation:
In the sample C program-
- We declare an integer variable x inside the main() function and initialize it with the value 10.
- Next, we use the division assignment operator (/=) to divide the value of x by 2 and assign the result of this operation back to variable x.
- Here, the expression x /= 2 can be expanded as x = x / 2, which ultimately divides the value of x by 2 and stores the result back into x.
- Finally, we display this output using the printf() function with a formatted string message.
Modulo Assignment Operator In C (%=)
The modulo assignment operator (%=) is a combination of the modulo arithmetic operator and assignment operator. It divides the value of the left-side operand by the right-side operand to calculate the remainder of this division. Then, it assigns the resulting remainder back to the variable on the left. Note that the value on the right can also be the value of another variable in the program.
Look at the example below to better understand how to apply this compound assignment operator in C programs.
Code Example:
Output:
The value of x is 3
Explanation:
In the sample C code-
- In the main() function, we declare a variable, x, of integer data type and initialize it with the value of 14.
- Then, we use the modulo assignment operator (%=) to calculate the remainder from the division of the variable on the left side by a specified value and assign the result back to that variable.
- In this example, we divide the value of x by 4 and reassign the remainder to it.
- That is, x %= 4 is equivalent to x = x % 4, which ultimately calculates the remainder when x is divided by 4 and stores the result back into x.
- This reassigned/ updated value of x is displayed on the console using the printf() function with a formatted string and %d format specifier.
Bitwise Assignment Operators In C
We have already discussed the most commonly used assignment operators in C programing language. There are a few other compound assignment operators that you must know about. These are the bitwise assignment operators, which first conduct the respective bitwise operation on the operands and then assign the result back to the left operand in the expression.
There are three types of bitwise assignment operators in C, which we have discussed ahead.
Bitwise AND Assignment Operator In C (&=)
The bitwise AND assignment operator (&=) performs a bitwise AND operation between the current value of the variable on the left (i.e., the left operand) and the value on the right (i.e., the right operand) and then assigns the result to the variable on the left. The value on the right can also be another variable.
The assignment operator example below showcases how this compound operator works.
Code Example:
Output:
The value of x is 4
Explanation:
In the C program sample, we define the main() function (which serves as the entry point) after including the <stdio.h> file.
- We then declare an integer variable called x and use the basic assignment operator to initialize it with the value 12.
- Next, we use the bitwise AND assignment operator (&=) to perform a bitwise AND operation between the value of the variable on the left side and a specified value, and then we assign the result back to that variable.
- The equation x &= 5, which implies x = x & 5, performs a bitwise AND between the value of x and 5 and stores the result back into x.
- We display the result of this operation to the console with the printf() function, a formatted string, and the %d specifier.
Hone your coding skills with the 100-Day Coding Sprint at Unstop and claim bragging rights now!
Bitwise OR Assignment Operator In C (|=)
The bitwise OR assignment operator (|=) performs a bitwise OR operation between the current value of the variable on the left and the value on the right and then assigns the result to the variable on the left. The example below showcases the use this compound assingment operator in C.
Code Example:
Output Window :
The value of x is 13
Code Explanation:
In the C code sample-
- In the main() function, we declare an integer variable x and initialize it with the value 12. This reserves a memory location to store an integer value.
- Next, using the bitwise OR assignment operator, we perform a bitwise OR operation between the value of the variable on the left side (i.e., 12) and a specified value (i.e., 5) and assign the result back to the left-side variable, i.e., x.
- The expression x |= 5 leads to the evaluation of x = x | 5, which performs a bitwise OR between the value of x and 5 and stores the result back into x.
- Then, we use the printf() function to display the result/ updated value of left operand x to the console. We also use a formatted string and the %d specifier inside printf().
Left Shift Assignment Operator In C (<<=)
The bitwise left shift assignment operator (<<=) first shifts the bits of the current value of the variable on the left (i.e., left-hand operand) by the number of positions specified by the value on the right. Then, it assigns the result of this operation back to the variable on the left.
Code Example:
Output:
The value of x is 40
Explanation:
In this assignment operator example, we first include the essential header file and then initiate the main() function.
- Inside main(), we declare an integer variable x and initialize it with the value 10. This step reserves a memory location to store an integer value and assigns the value 10 to x.
- Next, we apply the left shift assignment operator (<<=) on this variable to perform a left shift operation on its value by a specified number of bits (here, 2) and assign the result back to that variable.
- The equation x <<= 2 expands to x = x << 2, which performs a left shift on the value of x by 2 bits and stores the result back into x.
- We print the new value of the left-hand side variable x to the console using the printf() function.
Right Shift Assignment Operator In C (>>=)
The bitwise right shift assignment operator (>>=) begins by shifting the bits of the initial value of the variable on the left (i.e., left-hand operand) by the number of positions specified by the right-hand value and then assigns the result to the variable on the left.
Code Example:
Output:
The value of x is 5
Explanation:
In the assignment operator C example-
- Inside the main() function (which serves as the entry point for program execution), we declare an integer variable x and initialize it with the value 10.
- Next, we employ the right shift assignment operator (>>=) to shift the bits of the value on the left side (i.e., 10, the value of x) by a specified number of positions (i.e., 1) to the right. Then, assign the result back to the left-hand side variable.
- The equation x >>= 1 is equivalent to x = x >> 1, which performs a right shift operation on the value of x by 1 position and stores the result back into x.
- We publish this updated value of the variable x to the console using a formatted string and %d specifier inside the printf() function.
Also Read: Shift Operators In C | The Ultimate Guide With Code Examples
Precedence & Associativity Of Assignment Operators In C
In C, operators have a defined precedence that determines the order in which expressions are evaluated when multiple operators are present. Precedence helps in resolving which operator should be applied or evaluated first in an expression. Associativity, on the other hand, defines the direction in which operators of the same precedence level are processed.
Precedence of Assignment Operators In C
All assignment operators in C (=, +=, -=, *=, /=, %=, etc.) have lower precedence compared to most other operators, such as arithmetic operators (+, -, *, /), relational operators (<, >, <=, >=), and logical operators (&&, ||). This means that in an expression where assignment operators are used alongside other operators, the other operators are evaluated first before the assignment takes place.
In other words, the other operators take precedence over assignment operators when evaluating expressions in C programs. For example:
int a = 5;
int b = 10;
int c = a + b * 2;
In this expression, the multiplication operator (*) has higher precedence than the addition operator (+), and both have higher precedence than the assignment (=). Therefore, b * 2 is evaluated first, then the result is added to a, and finally, the sum is assigned to c.
Assignment Operator Associativity In C
Assignment operators in C have right-to-left associativity. This means that when multiple assignment operators are used in a single expression, the expression is evaluated from right to left.
int a, b, c;
a = b = c = 10;
In this case, the value 10 is first assigned to c, then the value of c is assigned to b, and finally, the value of b is assigned to a. Since every assignment operator associates from right to left, this evaluation happens from right to left.
This associativity of assignment operators in C is particularly important to understand when chaining assignments or combining them with other operations.
Table Of Assignment Operators In C
Here is a table listing all the assignment operators in C programming with a brief description and example.
Operator Name |
Operator Symbol |
Description |
Equivalent Of |
Example |
Simple Assignment Operator |
= |
It assigns the value on the right to the left-hand side variable. |
N/A |
x = 5; |
Addition Assignment Operator |
+= |
Adds the value on the right to the left-hand side variable. |
x = x + y; |
x += y; |
Subtraction Assignment Operator |
-= |
Subtracts the value on the right from the left-hand side variable value. |
x = x - y; |
x -= y; |
Multiplication Assignment Operator |
*= |
Multiplies the left-side variable by the value on the right. |
x = x * y; |
x *= y; |
Division Assignment Operator |
/= |
Divides the variable on the left by the value on the right. |
x = x / y; |
x /= y; |
Modulus Assignment Operator |
%= |
Computes the remainder after division of the left-hand operand by the value on the right. |
x = x % y; |
x %= y; |
Bitwise AND Assignment Operator |
&= |
Performs a bitwise AND operation on the two operands. |
x = x & y; |
x &= y; |
Bitwise OR Assignment Operator |
|= |
Performs a bitwise OR operation on the two operands. |
x = x | y; |
x |= y; |
Bitwise XOR Assignment Operator |
^= |
Performs a bitwise-exclusive-OR assignment operation. |
x = x ^ y; |
x ^= y; |
Left Shift Assignment Operator |
<<= |
Shifts the bits of the left-side variable to the left by as many bits as specified by the value on the right. |
x = x << y; |
x <<= y; |
Right Shift Assignment Operator |
>>= |
Shifts the bits of the left-side variable to the right by as many bits as specified by the value on the right. |
x = x >> y; |
x >>= y; |
Relational Vs. Assignment Operators In C
Both the relational and the assignment operators serve different purposes and have distinct characteristics in programming languages like C. Assignment operators deal with assigning values to operands/ variables. In contrast, relational operators focus on making comparisons between operands, thus enabling logical decision-making in control flow statements.
Here are some points highlighting the differences between relational and assignment operators in C:
Purpose | Relational Vs. Assignment Operators In C
Assignment Operators: Assignment operators are used to assign values or expressions to variables. They perform the task of storing a value in a variable.
Relational Operators: Relational operators are used to compare values or expressions. They determine the relationship between two operands and produce a Boolean result (true or false) based on the comparison.
Syntax | Relational Vs. Assignment Operators In C
Assignment Operators: Assignment operators are typically represented by a single character followed by an equal sign, such as (=), (+=), (-=), (*=), etc.
Relational Operators: Relational operators are represented by two or more characters, including equality operators (==, !=), other relational operators (<, >, <=, >=), etc.
Operation | Relational Vs. Assignment Operators In C
Assignment Operators: Assignment operators in C perform the task of assigning a value or expression to a variable. They modify the value of the left-hand side variable based on the right-hand side value or expression.
Relational Operators: Relational operators compare the values of two operands and return a Boolean result indicating whether the comparison is true or false.
Result Type | Relational Vs. Assignment Operators In C
Assignment Operators: In case of the simple assignment operator, the result is not a value in itself but the assignment of value to the variable on the left-hand side of the operator. But in case of compound assingment operators in C the result is the value assigned to the variable on the left-hand side of the operator, which can be used in further expressions or assignments.
Relational Operators: The result of a relational operator is a Boolean value, either true or false, indicating the outcome of the comparison.
Usage | Relational Vs. Assignment Operators In C
Assignment Operators: Assignment operators in C are primarily used for variable assignments, updating variables, and performing calculations involving the current value of a variable.
Relational Operators: Relational operators are used in conditional statements (if, while, for) and expressions that require comparison between variables or values.
Precedence | Relational Vs. Assignment Operators In C
Assignment Operators: Assignment operators in C have lower precedence compared to most other operators, which means they are evaluated after most other operations in an expression.
Relational Operators: Relational operators have higher precedence than assignment operators, allowing them to be evaluated before assignment operations.
Looking for mentors? Find the perfect mentor for select experienced coding & software experts here.
Conclusion
The assignment operator in C is one of the most important and commonly used operators in the language. It assigns values to variables, which is essential for writing any program. Compound assignment operators can be used to make code more concise and efficient. These assignment operators are fundamental operators that allow programmers to store and manipulate data effectively throughout their programs. It is important to understand the different types of assignment operators and how to use them correctly to write and run efficient and effective C code.
Also Read: 100+ Top C Interview Questions With Answers (2024)
Frequently Asked Questions
Q. What is an assignment operator in C?
An assignment operator is an operator in the C language that assigns a value to a variable. This could be a direct value (as in initialization) or the value that results from a compound operation (like the result of addition, subtraction, multiplication, etc. operations).
The most commonly used assignment operator is the equal sign (=), the basic assignment operator. It assigns the value on the right-hand side to the variable on the left-hand side of the operator.
Q. What is the difference between a simple assignment operator and a compound assignment operator?
The simple assignment operator, the equal-to operator (=), assigns a single value to a variable. On the other hand, a compound assignment operator in C (binary operator) performs a binary operation (such as addition, subtraction, multiplication, etc.) between the current value of a variable and another value or expression and then assigns the result to the variable. Its examples are- addition assignment (+=), multiplication assignment (*=), modulo assignment (%=), etc.
Q. What happens if I use an assignment operator with incompatible types in C?
Using an assignment operator with incompatible types in the C programming language results in a compilation error. C is a statically typed language, meaning variables must be explicitly declared with their data types, and the compiler enforces strict type-checking during the compilation process. If an attempt is made to assign a value of one type to a variable of a different, incompatible type without an explicit type conversion, the compiler will raise an error.
For example, trying to assign a character ('A') to an integer variable declared as int will lead to a compilation error. This mechanism helps catch potential type-related errors early in the development process, ensuring that the program adheres to the specified type rules and preventing unexpected behavior during runtime.
Q. Can I chain multiple assignment operators together in C language?
In the C programming language, it is possible to chain multiple assignment operators together in a single statement. That is, you can assign the same value to multiple variables in one line by chaining assignments. For example, the following code is valid in C:
int a, b, c;
a = b = c = 5; // This is not allowed in C
This assigns the value 5 to all three variables (a, b, and c). The expression is evaluated from right to left due to the right-associative nature of the assignment operators in C.
Q. Are there any precedence rules for assignment operators?
Yes, there are precedence rules for assignment operators in C language. The assignment operator (=) has a lower precedence than most other operators. This means that when an expression contains both assignment and other operators, the assignment will be performed after the evaluation of the other operators.
For example:
int a, b, c;
a = b = c = 5 + 3 * 2;
In this example, the multiplication (*) has higher precedence than the assignment (=). So, 3 * 2 is evaluated first, resulting in 6. Then, 5 + 6 is evaluated, resulting in 11. Finally, the assignment is performed from right to left, so c, b, and a will all be assigned the value 11.
It's important to note that associativity also plays a role. The assignment operators in C are right-associative, which means that when multiple assignments appear in a row, they are evaluated from right to left. In the example above, c = 5 + 3 * 2 is evaluated first, followed by b = c, and finally a = b.
Now that you know all about assignment operators in C, check out some other interesting topics:
- Increment And Decrement Operators In C With Precedence (+Examples)
- Keywords In C Language | Properties, Usage, Examples & Detailed Explanation
- Pointers In C | Ultimate Guide With Easy Explanations (+Examples)
- Ternary (Conditional) Operator In C Explained With Code Examples
- For Loop In C | Structure, Working & Variations With Code Examples