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.