==
: Equal to (equality operator)!=
: Not equal to (inequality operator)>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to#include <stdio.h>
int main() {
int a = 10;
int b = 20;
if(a > b) {
printf("a is greater than b.\n");
} else if (a == b) {
printf("a is equal to b.\n");
} else {
printf("a is less than b.\n");
}
return 0;
}
a is less than b.
What causes it: When you compare incompatible data types, such as comparing a string with an integer.
# Bad code example that triggers the error
int num = 10;
char* str = "20";
if (num == str) { /* This will cause a TypeError */ }
Error message:
Traceback (most recent call last):
File "example.c", line 5, in <module>
if (num == str) { /* This will cause a TypeError */ }
TypeError: Invalid argument type for unary operator '=='
Solution: Cast the data types to make them compatible before comparison or use functions like strcmp()
for string comparisons.
# Corrected code
if (num == atoi(str)) { /* Using atoi() function to convert string to integer */ }
Why it happens: Comparison requires both operands to have the same data type, and in this case, we're comparing an integer with a string.
How to prevent it: Always ensure that the data types you compare are compatible or use appropriate functions like strcmp()
for strings.
What causes it: When you try to compare a variable that has not been declared yet.
# Bad code example that triggers the error
int num = 10;
if (undec_var > num) { /* This will cause a NameError */ }
Error message:
Traceback (most recent call last):
File "example.c", line 3, in <module>
if (undec_var > num) { /* This will cause a NameError */ }
NameError: name 'undec_var' is not defined
Solution: Declare the variable before using it for comparison.
# Corrected code
int undec_var = 20;
if (undec_var > num) { }
Why it happens: The variable undec_var
is not defined in the given code, so the interpreter cannot perform comparison.
How to prevent it: Always declare variables before using them for comparisons.
==
or !=
with caution due to rounding errors that may cause unexpected results. Instead, consider using an epsilon value (small constant) for comparisons.strcmp()
for strings.Next steps for learning: Understand logical operators, conditional statements, and control structures further in C programming.