Skip to main content

Command Palette

Search for a command to run...

Relational, Logical, and Unary Operators

C Programming Series - Article 4

Published
7 min read
Relational, Logical, and Unary Operators
S

👋 Hey, I'm Shreya, a Senior Software Engineer in an Leading MNC. Join me on this blog as I share insights, tips, and experiences. Let's explore these fascinating worlds together! 🚀💻 #CodeAndSecure

In this guide, we will break down Relational, Logical, and Unary operators based on deep-dive lecture notes. We will also tackle the common traps that catch beginners off guard.


1. A "Fact" About C

The first thing you must understand—and the most important note from our study—is that Standard C (C89/90) has no Boolean data type. There is no true or false keyword.

Instead, C uses integers:

  • 0 represents False.

  • Any non-zero value (1, -5, 3.14, etc.) represents True.

Developer Note: When C outputs the result of a comparison (like 5 > 3), it will always produce the integer 1 for True and 0 for False.


2. Relational Operators: The Comparison Engine

Relational operators are used to compare values. They are the foundation of decision-making in your code.

OperatorDescriptionExample (Input)Result (Output)
>Greater Than10 > 51
<Less Than10 < 201
>=Greater/Equal10 >= 101
<=Less/Equal5 <= 51
==Equal To5 == 30
!=Not Equal To5 != 31

3. Logical Operators: Combining Conditions

Logical operators allow us to chain comparisons together. This is where the "Non-zero is True" rule becomes critical.

The Operators

  1. Logical AND (&&): Returns 1 only if both sides are True.

  2. Logical OR (||): Returns 1 if at least one side is True.

  3. Logical NOT (!): Inverts the value (Unary operator).

Truth Table for Logical Operators

| A1 | A2 | A1 && A2 | A1 || A2 | !A1 | !A2 | | --- | --- | --- | --- | --- | --- | | 0 | 0 | 0 | 0 | 1 | 1 | | 0 | non-zero | 0 | 1 | 1 | 0 | | non-zero | 0 | 0 | 1 | 0 | 1 | | non-zero | non-zero | 1 | 1 | 0 | 0 |

Detailed Examples (Edge Cases)

Let's look at how C handles specific scenarios, including floats and negative numbers.

Example: Logical AND (&&)

int result;

// 1. Standard Comparison
// Both 15 and 6 are non-zero. True && True.
result = 15 && 6; // Output: 1

// 2. The "Zero" Kill Switch
// Since the first number is 0 (False), the result is immediately 0.
result = 0 && 9; // Output: 0

// 3. Floating Point Numbers
// C treats 4.5 and 1.2 as non-zero, so they are True.
result = 4.5 && 1.2; // Output: 1

// 4. Negative Numbers
// -5 is non-zero, so it is True!
result = 10 && -5; // Output: 1

Example: The Compilation Error Trap

A specific note in our study highlights a syntax error that often confuses beginners.

// INCORRECT:
int a = 100 && ; 
// ERROR: Compilation Error. 
// Why? The && operator requires two operands. You cannot leave one side empty.

Example: Logical OR (||)

int b;
// 1. Short Circuiting
// The first value is 5 (True). C stops looking and returns 1.
b = 5 || 2; // Output: 1

// 2. Second Chance
// First is 0 (False), but second is 8 (True).
b = 0 || 8; // Output: 1

Example: Multiple AND Conditions

a = 7 - 9 && 4 > 3;
// Step 1: 7 - 9 = -2 (non-zero, so True)
// Step 2: 4 > 3 = 1 (True)
// Step 3: 1 && 1 = 1
// Output: a = 1

Example: OR with Zero Values

a = 6 || 4 > 0;
// Step 1: 6 is non-zero (True)
// Output: a = 1 (short-circuit evaluation)

Note: In C, any non-zero value is considered true (1), and zero is considered false (0).

4. The "No Assignment" Trap

This is a classic exam question. What happens if you perform a calculation but don't use the = operator?

The Logic:

"If there is no assignment operator, the value of the variable is not updated."

Code Analysis:

void main() {
    int a = 5;

    // We apply the NOT operator three times
    !!!a; 

    // Trace: 
    // 1. !5 (False) -> 0
    // 2. !0 (True)  -> 1
    // 3. !1 (False) -> 0
    // Result is 0. HOWEVER, we never wrote "a = ...".

    printf("%d", a); 
}

Output: 5 (The variable a remains untouched).


5. Operator Precedence: The Hierarchy

When you mix arithmetic (+, *), relational (>), and logical (&&) operators in one massive line, C follows a strict priority list.

The Priority Order (Top to Bottom):

  1. Unary Operators (!, -, ++, sizeof)

  2. Arithmetic (High) (*, /, %)

  3. Arithmetic (Low) (+, -)

  4. Relational (>, <, >=, <=) — Evaluated Left to Right

  5. Equality (==, !=)

  6. Logical AND (&&)

  7. Logical OR (||)

  8. Assignment (=)

Example 1:

Expression: result = 10 + 2 * 5 >= 40 % 3 <= 8 != 10 - 2 * 3 >= 12 + 2

Step-by-Step Solution:

  1. Arithmetic High (*, %):

    • 2 * 5 = 10

    • 40 % 3 = 1 (Remainder)

    • 2 * 3 = 6

    • Eq: 10 + 10 >= 1 <= 8 != 10 - 6 >= 12 + 2

  2. Arithmetic Low (+, -):

    • 10 + 10 = 20

    • 10 - 6 = 4

    • 12 + 2 = 14

    • Eq: 20 >= 1 <= 8 != 4 >= 14

  3. Relational (>=, <=) Left-to-Right:

    • 20 >= 1 is True (1).

    • Eq: 1 <= 8 != 4 >= 14

    • 1 <= 8 is True (1).

    • Eq: 1 != 4 >= 14

    • Wait! != is lower priority than >=. We must do the right side first.

    • 4 >= 14 is False (0).

    • Eq: 1 != 0

  4. Equality (!=):

    • 1 != 0 is True (1).
  5. Final Result: 1.


6. Floating Point Modulo (fmod)

Standard C does not allow the modulus operator (%) on floating-point numbers.

  • 5.5 % 2 -> Compilation Error.

To calculate the remainder for floats, you must use the math.h library:

#include <stdio.h>
#include <math.h> // Required header

void main() {
    double num = 5.5;
    double den = 2.0;

    // Correct way to find remainder
    double r = fmod(num, den); 

    printf("%lf", r); // Output: 1.5
}

7. Unary Operators

Unary operators are operators that perform operations on a single operand to produce a new value. Unlike binary operators (which require two operands), unary operators work with just one.

Types of Unary Operators:

  1. Unary Minus (-): Negates a value.

     a = -5; // a becomes -5
    
  2. Increment (++): Increases value by 1.

     a++; // Post-increment
     ++a; // Pre-increment
    
  3. Decrement (--): Decreases value by 1.

     a--; // Post-decrement
     --a; // Pre-decrement
    
  4. Logical NOT (!): Inverts state.

     !a; // Returns opposite boolean value
    
  5. Address Of (&): Fetches memory address.

     &a; // Returns address of variable a
    
  6. Size Of (sizeof): Returns byte size.

     sizeof(a); // Returns size of variable/data type
    

Bitwise NOT (~): Inverts all bits.

~a; // Bitwise complement

Important: Right-to-Left Evaluation

Unary operators are evaluated from right to left, which is unique from most other operators.

Example: Pre-increment

void main() {
    int a;
    a = 5;
    ++a;
    printf("%d", a);
    // Output: 6
}

Explanation:

  • Initial value: a = 5

  • Pre-increment ++a: First increments a to 6, then uses the value

  • Output: 6

8. Understanding Assignment Operators

Key Concept: If there is no assignment operator, the value of the variable is not updated.

Example with No Assignment:

a = 6;
a!; // Just evaluates, doesn't update
printf("a"); // Output: 6

Example with Assignment:

a = 6;
a = !a // 0
printf("a"); // Output: 0

📚 Navigate the Series