Start Coding

Topics

C Operators

Operators in C are symbols that perform specific operations on one or more operands. They are fundamental to C programming, allowing you to manipulate data and control program flow efficiently.

Types of C Operators

1. Arithmetic Operators

These operators perform mathematical calculations:

  • + (addition)
  • - (subtraction)
  • * (multiplication)
  • / (division)
  • % (modulus)

2. Relational Operators

Used for comparing values:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

3. Logical Operators

These operators perform logical operations:

  • && (logical AND)
  • || (logical OR)
  • ! (logical NOT)

4. Bitwise Operators

Operate on individual bits of integer values:

  • & (bitwise AND)
  • | (bitwise OR)
  • ^ (bitwise XOR)
  • ~ (bitwise NOT)
  • << (left shift)
  • >> (right shift)

5. Assignment Operators

Used to assign values to variables:

  • = (simple assignment)
  • +=, -=, *=, /=, %= (compound assignment)

Examples of C Operators in Action

Arithmetic and Assignment Operators


#include <stdio.h>

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

    result = a + b;
    printf("Addition: %d\n", result);

    result = a - b;
    printf("Subtraction: %d\n", result);

    result *= 2;
    printf("Multiplication and assignment: %d\n", result);

    return 0;
}
    

Relational and Logical Operators


#include <stdio.h>

int main() {
    int x = 5, y = 10;

    if (x < y && x != 0) {
        printf("x is less than y and not equal to zero\n");
    }

    if (x == 5 || y > 15) {
        printf("Either x is 5 or y is greater than 15\n");
    }

    return 0;
}
    

Operator Precedence

C operators follow a specific order of precedence. Understanding this order is crucial for writing correct expressions. For instance, multiplication has higher precedence than addition.

Best Practices

  • Use parentheses to clarify complex expressions and override default precedence.
  • Be cautious with C Type Casting when using operators with different data types.
  • Avoid using the comma operator in complex expressions to maintain readability.

Related Concepts

To deepen your understanding of C operators, explore these related topics:

Mastering C operators is essential for effective C programming. They form the backbone of expressions and control structures in your code. Practice using different operators to become proficient in manipulating data and controlling program flow.