C:C Operators: Arithmetic, Relational, and Bitwise Logic
C•Operators

C Operators: Arithmetic, Relational, and Bitwise Logic

Explore C operator precedence, integer division truncation, and low-level bitwise operations (&, |, ^, <<, >>).

Syntax

result = a + b; bitwise = flags & MASK;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&, |, ^Bitwise OperatorsBitwise AND, OR, and XOR.
<<, >>Bit Shift OperatorsShifts bits left (multiply by 2) or right (divide by 2).

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

#include <stdio.h>

int main(void) {
    int a = 25;
    int b = 4;

    printf("Addition:    %d + %d = %d\n", a, b, a + b);
    printf("Integer Div: %d / %d = %d (truncated)\n", a, b, a / b);
    printf("Float Div:   %.2f\n", (float)a / b);
    printf("Modulus:     %d %% %d = %d\n", a, b, a % b);

    // Bitwise shift: 1 shifted left by 4 positions = 16
    int bitShift = 1 << 4;
    printf("1 << 4 =     %d\n", bitShift);

    return 0;
}
Expected Output:
Addition:    25 + 4 = 29
Integer Div: 25 / 4 = 6 (truncated)
Float Div:   6.25
Modulus:     25 % 4 = 1
1 << 4 =     16

How It Works: Step-by-Step

  • Lines 7-10: Demonstrates integer truncation vs casted float division.
  • Lines 13-14: Uses bitwise shift 1 << 4 to evaluate 2^4 = 16.

Key Concepts

  • In C, division of two integers truncates toward zero.
  • C uses %% in printf to output a literal percent sign.
  • Bitwise operators work directly on underlying binary representation.

Common Mistake: Modulo % with floating-point numbers

In C, the % operator is only valid for integer operands. Use fmod() from <math.h> for doubles.

❌ Incorrect
double r = 5.5 % 2.0; // Compile Error: invalid operands to binary %
✅ Correct
int r = 5 % 2; // Valid integer modulo

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler