C Equal-To Operator

In C, the Equal-to == operator is a comparison operator used to check whether two values are equal. If both values are equal, the operator returns true (1); otherwise, it returns false (0).

The Equal-To == operator is commonly used in conditional statements like if and loop conditions.


Syntax of the Equal-To Operator

The syntax to use Equal-To operator is:

</>
Copy
variable1 == variable2

where:

  1. variable1: The first operand to compare.
  2. ==: The equal-to comparison operator.
  3. variable2: The second operand to compare with the first operand.

The result of the comparison is 1 (true) if both operands are equal, otherwise 0 (false).


Examples of the Equal-To Operator

1. Using Equal-To to Compare Two Integers

In this example, we will compare two integer values using the Equal-To == operator and print the result.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int a = 10, b = 10;

    if (a == b) {
        printf("Both numbers are equal.\n");
    } else {
        printf("Numbers are not equal.\n");
    }

    return 0;
}

Explanation:

  1. We declare two integer variables a and b, both initialized to 10.
  2. The if condition checks if a == b.
  3. Since 10 == 10 is true, the message “Both numbers are equal.” is printed.

Output:

Both numbers are equal.

2. Using Equal-To with Different Values

In this example, we will compare two different numbers to demonstrate when the Equal-To == operator returns false.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int x = 15, y = 20;

    if (x == y) {
        printf("Numbers are equal.\n");
    } else {
        printf("Numbers are not equal.\n");
    }

    return 0;
}

Explanation:

  1. We declare two integer variables x and y, with values 15 and 20.
  2. The condition x == y checks if the values are equal.
  3. Since 15 == 20 is false, the else block executes, printing “Numbers are not equal.”

Output:

Numbers are not equal.

3. Using Equal-To with Characters

In this example, we will compare character values using the Equal-To == operator.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char ch1 = 'A', ch2 = 'A';

    if (ch1 == ch2) {
        printf("Characters are equal.\n");
    } else {
        printf("Characters are not equal.\n");
    }

    return 0;
}

Explanation:

  1. We declare two character variables ch1 and ch2 with the value ‘A’.
  2. The condition ch1 == ch2 checks if both characters are the same.
  3. Since both are ‘A’, the condition is true, and “Characters are equal.” is printed.

Output:

Characters are equal.

Conclusion

In this tutorial, we covered the Equal-To == operator in C:

  1. The Equal-To == operator is used to check equality between two values.
  2. It returns 1 (true) if both values are equal and 0 (false) if they are not.
  3. It can be used with different data types, such as integers and characters.

The Equal-To == operator is essential for writing conditional statements and controlling program flow.