1. Introduction
In the C programming language, = and == are two operators that are often confused but serve very different purposes. = is an assignment operator, used to assign a value to a variable. == is a relational or comparison operator, used to compare two values for equality.
2. Key Points
1. = is used for assigning a value to a variable.
2. == is used to compare two values and returns a boolean result.
3. Using = in a place where == is intended is a common source of bugs in C programming.
4. == evaluates to 1 (true) if the comparison is true, and 0 (false) otherwise.
3. Differences
= (Assignment) | == (Comparison) |
---|---|
Used to assign a value to a variable. | Used to evaluate the equality of two expressions. |
Has a single equal sign (=). | Has two equal signs (==). |
Does not return a value. | Returns 1 if the comparison is true, else returns 0. |
4. Example
#include <stdio.h>
int main() {
int a;
a = 10; // Assignment
printf("Value of a: %d\n", a);
if (a == 10) { // Comparison
printf("a is equal to 10\n");
} else {
printf("a is not equal to 10\n");
}
return 0;
}
Output:
Value of a: 10 a is equal to 10
Explanation:
1. a = 10; assigns the value 10 to the variable a.
2. if (a == 10) checks if a is equal to 10, which is true in this case.
5. When to use?
- Use = when you need to assign a value to a variable.
- Use == when you need to compare two values for equality, typically inside conditional statements like if, while, or for.
Difference between malloc() and calloc()?
Difference between Local Variable and Global Variable in C
Difference between Global and Static Variables in C
Difference Between Call by Value and Call by Reference in C
Difference Between getch() and getche() in C
Difference between printf() and sprintf() in C
Difference between Arrays and Pointers in C
Difference between Structure and Union in C
Difference Between Stack and Heap Memory Allocation in C
Difference Between Macro and Function in C
Difference between = and == in C
Difference Between for loop and while loop in C
Difference Between Linked List and Array in C
Difference between fgets() and gets() in C
Difference between ++i and i++ in C
Difference between struct and typedef struct in C
Difference between int main() and void main() in C
Difference between Character Array and String in C
Comments
Post a Comment
Leave Comment