Operators in C Language| Part-4

Unary operators

Unary operator are those which only require one operand(argument) to operate. + , - , ++, --, typecast and sizeof are some unary operators in C programming.

+5, -5 are the example of +,- unary operators. which represents +ve and -ve values.

Unary operators have high priority than binary operators, so unary operators are always evalutes first.

Increment / Decrement operator

++, -- are called increment and decrement operators.

Increment and decrement operators are available in two versions

  1. Prefix
  2. Postfix

Difference b/w prefix and postfix

Prefix Postfix

int a = 5;
++a;
printf("%d",a); // 6


int a = 5;
a++;
printf("%d",a); // 6


int a = 5,b;
b = ++a;
printf("%d %d",a,b);// 6 6


int a = 5,b;
b = a++;
printf("%d %d",a,b);//6 5    

Example of increment and decrement operators

Example-1:


int a = 3, b = 4,c;
c = ++a * ++b;
printf("%d %d %d",a,b,c); //4 5 20 

Example-2:


int a = 3,b = 4, c;
c = a++ * b++;
printf("%d %d %d",a,b,c); // 4 5 12

Example-3:


int a = 3,b = 4, c;
c = ++a && b++;
printf("%d %d %d",a,b,c); //4 5 16

Example-4:


int a = 5,b;
b = a++ * a++;
printf("%d %d",a,b); // 7 25


int a = 5,b;
b = ++a * ++a;
printf("%d %d",a,b);

Above example, output varies from compiler to compiler. on some compiler output is 7 42 as expected most of the time. but on the other hand, some compiler produces 7 49. This happens because on some compiler when the value of a is changed on one place then it affects all places of the same expression.

Comma operator

  1. Comma operator is used to seperate one or more variables and value.
  2. Comma operator works from left to right, but returns right most value.
  3. Comma operator is the last one in the priority table of operator so it has the lowest priority in all operators.

Example-1

int a;
a = 5,6,7;
printf("%d",a); // 5
//because = operator enjoy the high priority than comma so it evalutes first and 5 gets stored in a.

Example-2

int a;
a = (5,6,7);
printf("%d",a); // 7
//Here the parenthisis is evaluted first and from multiple value right most value returns and gets stored in a so output is 7.

Previous Back to C Programming index Next

Comments

Popular posts from this blog

String in golang

Inline V/S Block Level Element

Arrays in C Language

Data Types in Go language

Printing in C programming

Variable Naming & Scope of Variable

Escape Sequence | Formatted Printing | Interview Questions

Floating point Data types in Go lang

Overview of Go lang

Literals in Java