Difference Between `==` and `=` Operators in C programming

Difference Between `==` and `=` Operators in C

Difference Between `==` and `=` Operators in C

In C programming, the `==` operator and the `=` operator serve different purposes and are used in different contexts. Understanding the difference between them is crucial for writing correct and effective code.

1. Assignment Operator (=)

The = operator is known as the assignment operator. It is used to assign a value to a variable.

int a = 5;   // Assigns the value 5 to the variable a

In this example, a is assigned the value 5. The assignment operator sets the variable on the left-hand side to the value on the right-hand side.

2. Equality Operator (==)

The == operator is known as the equality operator. It is used to compare two values to determine if they are equal.

int a = 5;
int b = 10;
if (a == b) {
    printf("a and b are equal");
} else {
    printf("a and b are not equal");
}

In this example, a == b checks if the value of a is equal to the value of b. The equality operator returns true if the values are equal and false otherwise.

Comparison Table

Operator Purpose Example Usage
= Assignment int a = 5; Used to assign a value to a variable
== Equality Comparison a == b Used to compare two values for equality
Note: Confusing the assignment operator with the equality operator is a common mistake. The assignment operator (=) changes the value of a variable, while the equality operator (==) simply compares values without altering them.

Comments

Popular Posts