c

examples

examples.c🔧
/*
 * ============================================================================
 * OPERATORS IN C - EXAMPLES
 * ============================================================================
 * This file demonstrates all types of operators in C.
 * 
 * Compile: gcc -Wall examples.c -o examples
 * Run: ./examples
 * ============================================================================
 */

#include <stdio.h>

/*
 * Example 1: Arithmetic Operators
 * -------------------------------
 * Basic mathematical operations.
 */
void example_arithmetic() {
    printf("\n=== Example 1: Arithmetic Operators ===\n");
    
    int a = 17, b = 5;
    
    printf("a = %d, b = %d\n\n", a, b);
    
    printf("Addition:       a + b = %d\n", a + b);
    printf("Subtraction:    a - b = %d\n", a - b);
    printf("Multiplication: a * b = %d\n", a * b);
    printf("Division:       a / b = %d (integer)\n", a / b);
    printf("Modulus:        a %% b = %d (remainder)\n", a % b);
    
    // Float division
    float fa = 17.0f, fb = 5.0f;
    printf("\nFloat division: %.1f / %.1f = %.2f\n", fa, fb, fa / fb);
    
    // Integer to float conversion
    printf("Mixed: %d / %d = %.2f (with cast)\n", a, b, (float)a / b);
    
    // Unary operators
    printf("\nUnary operators:\n");
    printf("-a = %d\n", -a);
    printf("+a = %d\n", +a);
}

/*
 * Example 2: Increment and Decrement
 * ----------------------------------
 * Pre and post increment/decrement.
 */
void example_increment_decrement() {
    printf("\n=== Example 2: Increment and Decrement ===\n");
    
    int x = 5, y;
    
    printf("Initial x = %d\n\n", x);
    
    // Pre-increment
    x = 5;
    y = ++x;
    printf("y = ++x: x = %d, y = %d (increment first)\n", x, y);
    
    // Post-increment
    x = 5;
    y = x++;
    printf("y = x++: x = %d, y = %d (use first, then increment)\n", x, y);
    
    // Pre-decrement
    x = 5;
    y = --x;
    printf("y = --x: x = %d, y = %d (decrement first)\n", x, y);
    
    // Post-decrement
    x = 5;
    y = x--;
    printf("y = x--: x = %d, y = %d (use first, then decrement)\n", x, y);
    
    // In expressions
    printf("\nIn expressions:\n");
    x = 5;
    printf("x = %d, x + 1 = %d, x = %d (no change)\n", x, x + 1, x);
    x = 5;
    printf("x = %d, ++x = %d, x = %d (changed)\n", 5, ++x, x);
}

/*
 * Example 3: Relational Operators
 * -------------------------------
 * Comparison operators.
 */
void example_relational() {
    printf("\n=== Example 3: Relational Operators ===\n");
    
    int a = 10, b = 20, c = 10;
    
    printf("a = %d, b = %d, c = %d\n\n", a, b, c);
    
    printf("a == b: %d (false)\n", a == b);
    printf("a == c: %d (true)\n", a == c);
    printf("a != b: %d (true)\n", a != b);
    printf("a < b:  %d (true)\n", a < b);
    printf("a > b:  %d (false)\n", a > b);
    printf("a <= c: %d (true)\n", a <= c);
    printf("a >= b: %d (false)\n", a >= b);
    
    // Chained comparisons (don't work like math!)
    printf("\nChained comparison pitfall:\n");
    int x = 5;
    // if (1 < x < 10) - This doesn't work as expected!
    printf("1 < 5 < 10 expressed as: (1 < x) < 10\n");
    printf("(1 < x) = %d, then %d < 10 = %d\n", 1 < x, 1 < x, (1 < x) < 10);
    printf("Correct way: (1 < x) && (x < 10) = %d\n", (1 < x) && (x < 10));
}

/*
 * Example 4: Logical Operators
 * ----------------------------
 * AND, OR, NOT operators.
 */
void example_logical() {
    printf("\n=== Example 4: Logical Operators ===\n");
    
    int a = 1, b = 0;  // 1 = true, 0 = false
    
    printf("a = %d (true), b = %d (false)\n\n", a, b);
    
    // AND
    printf("Logical AND (&&):\n");
    printf("a && a = %d\n", a && a);  // 1
    printf("a && b = %d\n", a && b);  // 0
    printf("b && a = %d\n", b && a);  // 0
    printf("b && b = %d\n", b && b);  // 0
    
    // OR
    printf("\nLogical OR (||):\n");
    printf("a || a = %d\n", a || a);  // 1
    printf("a || b = %d\n", a || b);  // 1
    printf("b || a = %d\n", b || a);  // 1
    printf("b || b = %d\n", b || b);  // 0
    
    // NOT
    printf("\nLogical NOT (!):\n");
    printf("!a = %d\n", !a);  // 0
    printf("!b = %d\n", !b);  // 1
    printf("!!a = %d\n", !!a);  // 1 (double negation)
    
    // Complex conditions
    int age = 25, hasLicense = 1, hasInsurance = 0;
    printf("\nComplex conditions:\n");
    printf("age = %d, hasLicense = %d, hasInsurance = %d\n", 
           age, hasLicense, hasInsurance);
    printf("age >= 18 && hasLicense = %d\n", age >= 18 && hasLicense);
    printf("hasLicense || hasInsurance = %d\n", hasLicense || hasInsurance);
}

/*
 * Example 5: Short-Circuit Evaluation
 * -----------------------------------
 * How && and || skip evaluation.
 */
void example_short_circuit() {
    printf("\n=== Example 5: Short-Circuit Evaluation ===\n");
    
    int x = 0, y = 1;
    int counter = 0;
    
    // AND short-circuit: if first is false, second not evaluated
    printf("AND short-circuit:\n");
    counter = 0;
    if (x && (counter = 1)) { }
    printf("x && (counter = 1): counter = %d (not executed)\n", counter);
    
    counter = 0;
    if (y && (counter = 1)) { }
    printf("y && (counter = 1): counter = %d (executed)\n", counter);
    
    // OR short-circuit: if first is true, second not evaluated
    printf("\nOR short-circuit:\n");
    counter = 0;
    if (y || (counter = 1)) { }
    printf("y || (counter = 1): counter = %d (not executed)\n", counter);
    
    counter = 0;
    if (x || (counter = 1)) { }
    printf("x || (counter = 1): counter = %d (executed)\n", counter);
    
    // Practical example: null check
    printf("\nPractical use - null check:\n");
    int *ptr = NULL;
    // if (ptr != NULL && *ptr > 0)  // Safe: won't dereference if NULL
    printf("ptr != NULL && *ptr > 0: Won't crash if ptr is NULL\n");
}

/*
 * Example 6: Bitwise Operators
 * ----------------------------
 * Bit-level operations.
 */
void example_bitwise() {
    printf("\n=== Example 6: Bitwise Operators ===\n");
    
    unsigned char a = 0b00001111;  // 15
    unsigned char b = 0b00110011;  // 51
    
    printf("a = %d (binary: 00001111)\n", a);
    printf("b = %d (binary: 00110011)\n\n", b);
    
    // AND
    printf("a & b  = %3d (00000011) - bits set in both\n", a & b);
    
    // OR
    printf("a | b  = %3d (00111111) - bits set in either\n", a | b);
    
    // XOR
    printf("a ^ b  = %3d (00111100) - bits different\n", a ^ b);
    
    // NOT
    printf("~a     = %3d (11110000 as unsigned char)\n", (unsigned char)~a);
    
    // Left shift
    printf("\nLeft shift (multiply by 2):\n");
    printf("a << 1 = %3d (%d * 2)\n", a << 1, a);
    printf("a << 2 = %3d (%d * 4)\n", a << 2, a);
    printf("a << 3 = %3d (%d * 8)\n", a << 3, a);
    
    // Right shift
    printf("\nRight shift (divide by 2):\n");
    unsigned char c = 240;
    printf("240 >> 1 = %3d (240 / 2)\n", c >> 1);
    printf("240 >> 2 = %3d (240 / 4)\n", c >> 2);
    printf("240 >> 4 = %3d (240 / 16)\n", c >> 4);
}

/*
 * Example 7: Bit Manipulation
 * ---------------------------
 * Practical bitwise operations.
 */
void example_bit_manipulation() {
    printf("\n=== Example 7: Bit Manipulation ===\n");
    
    unsigned int flags = 0;  // All bits off
    
    // Set bit (turn ON)
    printf("Setting bits:\n");
    flags |= (1 << 0);  // Set bit 0
    printf("After setting bit 0: %u (binary: %d%d%d%d)\n", 
           flags, (flags>>3)&1, (flags>>2)&1, (flags>>1)&1, flags&1);
    
    flags |= (1 << 2);  // Set bit 2
    printf("After setting bit 2: %u (binary: %d%d%d%d)\n", 
           flags, (flags>>3)&1, (flags>>2)&1, (flags>>1)&1, flags&1);
    
    // Check bit
    printf("\nChecking bits:\n");
    printf("Bit 0 is %s\n", (flags & (1 << 0)) ? "SET" : "CLEAR");
    printf("Bit 1 is %s\n", (flags & (1 << 1)) ? "SET" : "CLEAR");
    printf("Bit 2 is %s\n", (flags & (1 << 2)) ? "SET" : "CLEAR");
    
    // Clear bit (turn OFF)
    printf("\nClearing bit 0:\n");
    flags &= ~(1 << 0);
    printf("After clearing bit 0: %u\n", flags);
    
    // Toggle bit (flip)
    printf("\nToggling bit 2:\n");
    flags ^= (1 << 2);
    printf("After toggle 1: %u\n", flags);
    flags ^= (1 << 2);
    printf("After toggle 2: %u\n", flags);
    
    // Check if even/odd
    printf("\nEven/Odd check using & 1:\n");
    for (int i = 1; i <= 5; i++) {
        printf("%d is %s\n", i, (i & 1) ? "odd" : "even");
    }
    
    // Swap without temp
    printf("\nSwap using XOR:\n");
    int x = 5, y = 10;
    printf("Before: x = %d, y = %d\n", x, y);
    x ^= y;
    y ^= x;
    x ^= y;
    printf("After:  x = %d, y = %d\n", x, y);
}

/*
 * Example 8: Assignment Operators
 * -------------------------------
 * Compound assignment operators.
 */
void example_assignment() {
    printf("\n=== Example 8: Assignment Operators ===\n");
    
    int a = 20;
    printf("Initial a = %d\n\n", a);
    
    a = 20; a += 5;  printf("a += 5:  a = %d\n", a);
    a = 20; a -= 5;  printf("a -= 5:  a = %d\n", a);
    a = 20; a *= 5;  printf("a *= 5:  a = %d\n", a);
    a = 20; a /= 5;  printf("a /= 5:  a = %d\n", a);
    a = 20; a %= 6;  printf("a %%= 6:  a = %d\n", a);
    
    printf("\nBitwise compound:\n");
    a = 0b1111; a &= 0b0101; printf("0b1111 &= 0b0101: a = %d\n", a);
    a = 0b1111; a |= 0b0101; printf("0b1111 |= 0b0101: a = %d\n", a);
    a = 0b1111; a ^= 0b0101; printf("0b1111 ^= 0b0101: a = %d\n", a);
    a = 8;      a <<= 2;     printf("8 <<= 2: a = %d\n", a);
    a = 32;     a >>= 2;     printf("32 >>= 2: a = %d\n", a);
    
    // Chain assignment
    printf("\nChain assignment:\n");
    int x, y, z;
    x = y = z = 10;
    printf("x = y = z = 10: x=%d, y=%d, z=%d\n", x, y, z);
}

/*
 * Example 9: Ternary Operator
 * ---------------------------
 * Conditional expression.
 */
void example_ternary() {
    printf("\n=== Example 9: Ternary Operator ===\n");
    
    int a = 10, b = 20;
    int max, min;
    
    // Find max and min
    max = (a > b) ? a : b;
    min = (a < b) ? a : b;
    printf("a = %d, b = %d\n", a, b);
    printf("max = %d, min = %d\n", max, min);
    
    // Absolute value
    int x = -5;
    int abs_x = (x < 0) ? -x : x;
    printf("\nAbsolute value of %d: %d\n", x, abs_x);
    
    // Even or odd
    printf("\nEven or odd:\n");
    for (int i = 1; i <= 5; i++) {
        printf("%d is %s\n", i, (i % 2 == 0) ? "even" : "odd");
    }
    
    // Nested ternary (use sparingly!)
    int score = 75;
    char *grade = (score >= 90) ? "A" :
                  (score >= 80) ? "B" :
                  (score >= 70) ? "C" :
                  (score >= 60) ? "D" : "F";
    printf("\nScore %d = Grade %s\n", score, grade);
    
    // In printf
    int count = 1;
    printf("\n%d item%s\n", count, (count == 1) ? "" : "s");
    count = 5;
    printf("%d item%s\n", count, (count == 1) ? "" : "s");
}

/*
 * Example 10: sizeof Operator
 * ---------------------------
 * Getting size of types and variables.
 */
void example_sizeof() {
    printf("\n=== Example 10: sizeof Operator ===\n");
    
    // Size of types
    printf("Size of basic types:\n");
    printf("sizeof(char)   = %zu byte\n", sizeof(char));
    printf("sizeof(short)  = %zu bytes\n", sizeof(short));
    printf("sizeof(int)    = %zu bytes\n", sizeof(int));
    printf("sizeof(long)   = %zu bytes\n", sizeof(long));
    printf("sizeof(float)  = %zu bytes\n", sizeof(float));
    printf("sizeof(double) = %zu bytes\n", sizeof(double));
    printf("sizeof(void*)  = %zu bytes\n", sizeof(void*));
    
    // Size of variables
    int x = 42;
    double d = 3.14;
    printf("\nSize of variables:\n");
    printf("sizeof(x) = %zu bytes\n", sizeof(x));
    printf("sizeof(d) = %zu bytes\n", sizeof(d));
    
    // Size of arrays
    int arr[10];
    printf("\nSize of arrays:\n");
    printf("sizeof(arr) = %zu bytes\n", sizeof(arr));
    printf("Number of elements = %zu\n", sizeof(arr) / sizeof(arr[0]));
    
    // Size of expressions
    printf("\nsizeof expressions:\n");
    printf("sizeof(x + d) = %zu (promoted to double)\n", sizeof(x + d));
    printf("sizeof(x + 1) = %zu (still int)\n", sizeof(x + 1));
}

/*
 * Example 11: Operator Precedence
 * -------------------------------
 * Order of evaluation matters!
 */
void example_precedence() {
    printf("\n=== Example 11: Operator Precedence ===\n");
    
    int a = 2, b = 3, c = 4;
    
    // Arithmetic precedence
    printf("Arithmetic precedence:\n");
    printf("2 + 3 * 4 = %d (not 20!)\n", 2 + 3 * 4);
    printf("(2 + 3) * 4 = %d\n", (2 + 3) * 4);
    
    // Mixed operators
    printf("\nMixed operators:\n");
    printf("10 - 4 - 2 = %d (left to right)\n", 10 - 4 - 2);
    printf("10 - (4 - 2) = %d\n", 10 - (4 - 2));
    
    // Relational and logical
    printf("\nRelational and logical:\n");
    printf("2 < 3 && 4 > 1 = %d\n", 2 < 3 && 4 > 1);
    printf("2 < (3 && 4) > 1 = %d (wrong logic!)\n", 2 < (3 && 4));
    
    // Assignment precedence
    printf("\nAssignment precedence:\n");
    int x, y, z;
    x = y = z = 5;  // Right to left
    printf("x = y = z = 5: x=%d, y=%d, z=%d\n", x, y, z);
    
    // Bitwise precedence pitfall
    printf("\nBitwise precedence pitfall:\n");
    int val = 5;
    printf("val & 1 == 0: %d (& has lower precedence than ==!)\n", val & 1 == 0);
    printf("(val & 1) == 0: %d (correct way)\n", (val & 1) == 0);
}

/*
 * Example 12: Comma Operator
 * --------------------------
 * Multiple expressions in one statement.
 */
void example_comma() {
    printf("\n=== Example 12: Comma Operator ===\n");
    
    int a, b, c;
    
    // Comma operator evaluates left to right, returns rightmost
    a = (b = 5, c = 10, b + c);
    printf("a = (b = 5, c = 10, b + c): a = %d\n", a);
    
    // In for loop
    printf("\nIn for loop:\n");
    for (a = 0, b = 10; a < b; a++, b--) {
        printf("a = %d, b = %d\n", a, b);
    }
    
    // Multiple operations
    int x = 0;
    x++, printf("After first increment: x = %d\n", x);
    x++, printf("After second increment: x = %d\n", x);
}

/*
 * Main Function
 */
int main() {
    printf("╔════════════════════════════════════════════════╗\n");
    printf("║    OPERATORS IN C - EXAMPLES                   ║\n");
    printf("║    Understanding all C operators               ║\n");
    printf("╚════════════════════════════════════════════════╝\n");
    
    example_arithmetic();
    example_increment_decrement();
    example_relational();
    example_logical();
    example_short_circuit();
    example_bitwise();
    example_bit_manipulation();
    example_assignment();
    example_ternary();
    example_sizeof();
    example_precedence();
    example_comma();
    
    printf("\n=== All Examples Completed! ===\n");
    
    return 0;
}
Examples - C Programming Tutorial | DeepML