Special Operators

Special Operators

Published by: Nuru

Published date: 21 Jun 2021

Special Operators Photo

Special Operators

C supports some special operators such as comma operator (,), size of operator, pointer operators (& and *) and member selection operators (. and ->). We discuss the comma and size of operator here.

Comma Operator

  • The comma is frequently used in C as a simple punctuation mark, serving to separate variable declarations, function arguments, and so on.
  • In certain situations, the comma acts as an operator as we can form an expression by separating two sub-expressions with a comma. The result is as follows:
  • Both expressions are evaluated, with the left expression being evaluated first. The entire expression evaluates to the value of the right expression.
  • For example, the following statement assigns the value of b to x, then increments a, and then increments b:

x = (a++ , b++);

  • Because the ++ operator is used in postfix mode, the value of b, before it is incremented, is assigned to x. Using parentheses is necessary because the comma operator has low precedence, even lower than the assignment operator.
  • The use of comma operator is used in for looping construct as:

for(n=1,m=10;n<=m;n++,n++)

  • exchanging values: t = x,x = y,y = t;
  • The other types of special operators used in C are pointer operators(&,*), member operators(.and ->),function operator (), array operator []etc.
  • The comma operator is mostly used in loops.

sizeof operator

  • The sizeof operator is used with an operand to return the number of bytes the operand occupies.

  • It is a compile-time operator.

  • The operand may be a constant, variable, or a data type qualifier.

/* An example for Comma operator */
#include
main()
{
int x,y,a=12,b=15;
int t;
x=(a++,b++);
printf("a=%d,b=%d,x=%d",a,b,x);
y=(b++,a++,x++);
printf("\na=%d,b=%d,x=%d,y=%d",a,b,x,y);
t = x,x = y,y = t;
printf("\nx=%d,y=%d",x,y);
getch();
return 0;
}

The Conditional Operator

  • The conditional operator is C's only ternary operator, meaning that it takes three operands. Its syntax is

exp1 ? exp2 : exp3;

  • If exp1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2. If exp1 evaluates to false (that is, zero), the entire expression evaluates as the value of exp3.
  • For example, the following statement assigns the value 1 to x if exp is true and assigns 100 to x if exp is false:

x = exp ? 1 : 100;

  • Likewise, to make z equal to the larger of x and y, we can write

z = (x > y)? x: y;

Conditional operator functions somewhat like an if statement. The preceding statements could also be written like this:
if(exp)x = 1; else x=100; and if (x > y) z = x; else z = y;