Course Topics
C Basics Introduction and Setup Syntax and Program Structure Comments and Documentation Compiling and Running C Programs Exercise Variables and Data Types Variables and Declaration Data Types (int, float, char, double) Constants and Literals Type Conversion and Casting Exercise Operators Arithmetic Operators Comparison Operators Logical Operators Assignment Operators Bitwise Operators Exercise Input and Output Standard Input/Output (scanf, printf) Format Specifiers File Input/Output Exercise Control Flow - Conditionals If Statements If-Else Statements Switch Statements Nested Conditionals Exercise Control Flow - Loops For Loops While Loops Do-While Loops Loop Control (break, continue) Nested Loops Exercise Functions Defining Functions Function Parameters and Arguments Return Statements Scope and Variables Recursion Exercise Arrays One-Dimensional Arrays Multi-Dimensional Arrays Array Operations Strings as Character Arrays Exercise Pointers Introduction to Pointers Pointer Arithmetic Pointers and Arrays Pointers and Functions Dynamic Memory Allocation Exercise Strings String Handling String Functions (strlen, strcpy, strcmp) String Manipulation Exercise Structures Defining Structures Structure Members Arrays of Structures Pointers to Structures Exercise File Handling Opening and Closing Files Reading from Files Writing to Files File Positioning Exercise Memory Management Static vs Dynamic Memory malloc() and free() Memory Leaks Best Practices Exercise Advanced Topics Preprocessor Directives Macros Header Files Modular Programming Exercise Final Project Project Planning Building Complete Application Code Organization Testing and Debugging Exercise

Comparison Operators

Introduction

  • Understanding comparison operators is crucial as they allow your program to make decisions based on the relationship between values.
  • In this lesson, you'll learn about various comparison operators in C language and their usage.

Core Concepts

  • Comparison Operators are symbols that determine if an expression is true or false by comparing two operands. The operands can be variables, constants, expressions, or even the result of a function call.

Comparison Operators in C:

  1. == : Equal to (equality operator)
  2. != : Not equal to (inequality operator)
  3. > : Greater than
  4. < : Less than
  5. >= : Greater than or equal to
  6. <= : Less than or equal to

Practical Examples

  • Let's see an example of using comparison operators:
#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;
}
  • Output: a is less than b.

Common Issues and Solutions

TypeError

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.

NameError

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.

Best Practices

  • Always use parentheses for clarity when combining logical expressions with comparison operators.
  • When comparing floating-point numbers, use == or != with caution due to rounding errors that may cause unexpected results. Instead, consider using an epsilon value (small constant) for comparisons.

Key Takeaways

  • Comparison operators in C allow you to evaluate relationships between values and make decisions based on those evaluations.
  • Be mindful of data types when comparing variables, and ensure that they are compatible or use appropriate functions like strcmp() for strings.
  • Declare all variables before using them in comparisons to avoid NameError.
  • Use parentheses for clarity when combining logical expressions with comparison operators.
  • Consider using an epsilon value when comparing floating-point numbers due to rounding errors.

Next steps for learning: Understand logical operators, conditional statements, and control structures further in C programming.