In C programming, assignment and conditional operators play a major role in setting values and making decisions. They help write clean, concise, and efficient code.
Let’s understand them in depth.
PART 1: Assignment Operators in C
Assignment operators are used to assign values to variables. They not only store values but can also perform operations while assigning.
The basic assignment operator is:
=
But C also includes several compound assignment operators.
1. Simple Assignment Operator (=)
This operator assigns a value to a variable.
Syntax
variable = value;
Example
int x = 10;
float y = 5.75;
2. Compound Assignment Operators
C provides operators that combine arithmetic or bitwise operations with assignment.
| Operator | Meaning | Equivalent To |
|---|---|---|
+= | Add and assign | a += b → a = a + b |
-= | Subtract and assign | a = a - b |
*= | Multiply and assign | a = a * b |
/= | Divide and assign | a = a / b |
%= | Modulus and assign | a = a % b |
&= | Bitwise AND and assign | a = a & b |
^= | Bitwise XOR and assign | a = a ^ b |
| ` | =` | Bitwise OR and assign |
<<= | Left shift and assign | a = a << b |
>>= | Right shift and assign | a = a >> b |
Examples of Compound Assignment Operators
Example 1: Using +=
int a = 10;
a += 5; // a = 15
Example 2: Using *=
int x = 4;
x *= 3; // x = 12
Example 3: Using <<=
int n = 2;
n <<= 2; // n = 2 * 2^2 = 8
Compound operators make code shorter and more efficient.
PART 2: Conditional Operator ( ?: )
The conditional operator, also known as the ternary operator, is the only operator in C that takes three operands.
It is used to replace simple if…else statements.
Syntax
condition ? expression1 : expression2;
- If condition is true,
expression1runs - If condition is false,
expression2runs
1. Basic Example
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Maximum = %d", max);
Output
Maximum = 20
2. Equivalent if…else
if (a > b)
max = a;
else
max = b;
Ternary operator makes it shorter and cleaner.
3. Nested Conditional Operator
Used to check multiple conditions.
int marks = 85;
char grade = (marks >= 90) ? 'A' :
(marks >= 75) ? 'B' :
(marks >= 50) ? 'C' : 'D';
printf("Grade: %c", grade);
4. Real-World Example
Checking even or odd
int n = 7;
printf("%d is %s", n, (n % 2 == 0) ? "Even" : "Odd");
Example Using Both Operator Types Together
#include <stdio.h>
int main() {
int a = 5, b = 3;
a += 2; // a = 7
int max = (a > b) ? a : b;
printf("a = %d\n", a);
printf("Maximum = %d", max);
return 0;
}
Conclusion
Assignment operators help simplify mathematical and bitwise operations during variable assignment, while the conditional (ternary) operator helps write compact decision-making logic. Mastering these operators will make your C programs cleaner, shorter, and more efficient.
🔗 View other articles about C Programming:
https://savanka.com/category/learn/c-programming