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:
variable1 == variable2where:
- variable1: The first operand to compare.
- ==: The equal-to comparison operator.
- 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
#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:
- We declare two integer variables aandb, both initialized to 10.
- The ifcondition checks ifa == b.
- Since 10 == 10is 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
#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:
- We declare two integer variables xandy, with values 15 and 20.
- The condition x == ychecks if the values are equal.
- Since 15 == 20is false, theelseblock 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
#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:
- We declare two character variables ch1andch2with the value ‘A’.
- The condition ch1 == ch2checks if both characters are the same.
- 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:
- The Equal-To ==operator is used to check equality between two values.
- It returns 1(true) if both values are equal and0(false) if they are not.
- 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.
