Conditional Operator or Ternary Operator in C Language

Mastering Conditional and Bitwise Operators in C Programming

In the vast realm of C programming, mastering operators is crucial. This article focuses on two powerful categories: Conditional and Bitwise Operators.

Conditional Operator: The Ternary Marvel

The Conditional Operator, also known as the Ternary Operator, operates on three operands, denoted as exp1 ? exp2 : exp3. Here, exp1 is evaluated first; if true, exp2 is assessed, otherwise exp3. Let's delve into examples:


int a = 5, b = 10, c = 15;
y = (a > b) ? b : c;

If a > b is false, c is assigned to y, making y equal to 15.


int a = 5, b = 10, c = 15;
y = (a < b) ? b : c;

Here, as a < b is true, b is assigned to y, resulting in y being 10.


x = (a > b && a > c) ? a : (b > c ? b : c);

This calculates the greatest of three numbers using conditional operators.

Bitwise Operators: Manipulating at the Bit Level

C introduces special operators for bit-level manipulation, catering to testing and shifting bits. These operators include &, |, ^, <<, >>, and ~. Here's a rundown:

  • & (Bitwise AND): Performs bitwise AND on individual bits.
  • | (Bitwise OR): Executes bitwise OR on individual bits.
  • ^ (Bitwise Exclusive-OR): Applies bitwise XOR on individual bits.
  • << (Shift Left): Left shifts binary bits.
  • >> (Shift Right): Right shifts binary bits.
  • ~ (One's complement): Inverts all bits.

Example


int a = 4, b = 6;
int c = a & b;  // c = 4
int d = a | b;  // d = 6
int e = a ^ b;  // e = 2
int f = a << 2; // f = 16
int g = a >> 2; // g = 1
int h = ~a;     // h = -5


-3 & 4 = 4, 5 & -8 = 0, -15 & -29 = -31
-7 | 4 = -3, 12 | -6 = -2, -24 | -9 = -1
-5 ^ 6 = -3, 9 ^ -14 = -5, -4 ^ -9 = 11
-15 << 6 = -960, -23 << 4 = -368, -14 >> 9 = -1, -5 >> 1 = -3
~undefined-18) = 17, ~7 = -8, ~undefined-3) = 2, ~undefined-27) = 26

In conclusion, mastering these operators unlocks advanced coding techniques. Understanding their nuances empowers programmers to craft efficient and optimized C programs.

Previous: Increment and Decrement Operators | Next: Special Operators in C

Post a Comment

0 Comments