Use of pre/post Increment operator in expression

In this example we will be learning very typical example of C Program where we will be using pre increment and post increment operators in same expression.

Re-commanded Reading : Increment Operator in C | Decrements Operator in C

Postfix and Prefix Expression in Same Statement

#include<stdio.h>
#include<conio.h>
void main() {
   int i = 0, j = 0;
   j = i++ + ++i;
   printf("%d\n", i);
   printf("%d\n", j);
}

Output :

2
2

Explanation of Program

A picture worth 100 lines of text. Consider the below program picture which explains the above program.

j = i++ + ++i;

Above line of code have total four operators -

  1. Assignment Operator
  2. Post Increment Operator
  3. Pre Increment Operator
  4. Arithmetic Operator

Now we need to arrange all the operators in the decreasing order of the Precedence -

OperatorPrecedence Rank
Pre Increment1
Post Increment2
Arithmetic Operator3
Assignment Operator4

Now we have arranged all the operators in the decreasing order of the precedence. (Operator Precedence and Associativity Document)

Execution flow

  1. In the first step pre-increment operator gets an opportunity for execution. It will increment the value of variable
  2. In the second step post increment operator will be executed. It does not increment the actual value of variable but mark it as pending execution.
  3. Here pre-increment operation uses new Value of ‘i’ so [ i = 1 ].
  4. This ‘i = 1’ is used for Post Increment Operation which uses Old Value i.e [i = 1] .
  5. Both ‘1’s are added and value 2 is assigned to ‘j’.

Summary :

Step 1 : j = i++ + 1;
Step 2 : j = 1 + 1; (post-increment pending on i)
Step 3 : j = 2; (Addition)
Step 4 : j = 2; (Assignment)
Step 5 : Pending increment on i will be executed

C multiple increment operators inside printf

We have already learnt different ways of using increment operators in c programming. In this tutorial we will study the impact of using multiple increment / decrement operators in printf.

Re-commanded Article : Use of Pre/Post increment operator in same expression

Multiple increment operators inside printf

#include<stdio.h>
void main() {
   int i = 1;
   printf("%d %d %d", i, ++i, i++);
}

Output :

3 3 1

Pictorial representation

Sequence of Printing Evaluating Expressions in Printf

Explanation of program

I am sure you will get confused after viewing the above image and output of program.

  1. Whenever more than one format specifiers (i.e %d) are directly or indirectly related with same variable (i,i++,++i) then we need to evaluate each individual expression from right to left.
  2. As shown in the above image evaluation sequence of expressions written inside printf will be - i++,++i,i
  3. After execution we need to replace the output of expression at appropriate place
NoStepExplanation
1Evaluate i++At the time of execution we will be using older value of i = 1
2Evaluate ++iAt the time of execution we will be increment value already modified after step 1 i.e i = 3
2Evaluate iAt the time of execution we will be using value of i modified in step 2

Below is programmatic representation of intermediate steps -

After Step 1 : printf("%d %d %d",i,++i,1);
After Step 2 : printf("%d %d %d",i,3,1);
After Step 3 : printf("%d %d %d",3,3,1);
After Step 4 : Output displayed - 3,3,1

After solving expressions printing sequence will : i, ++i, i++

Examples of typical expresssions

Post increment operator in expression

We have already studied the pre and post increment operators in c programming. In this tutorial we will be learning different examples of post increment operator.

Examples of post increment operator in expression

Before going through the different examples we can consider below values as initial values for each program explained below -

int i=0,j=0;
int k = 0;
int temp=3;

Depending upon these initial values try to grasp the below programs -

1.Post Increment Verity No 1

int main() {
   int num = 0, result = 0, i = 0;
   for (i = 0; i < 5; i++) {
      result = num++;
      printf("%d", result);
   }
   return 0;
}

Output : [ 0 1 2 3 4 ]

Consider the above program where we have used following statement -

result = num++;

num++ is a post increment which means we are firstly assigning the old value of variable ‘num’ to ‘result’. After assigning the older value of ‘result’ we will be increment value of ‘num’

2.Post Increment Verity No 2

int main() {
   int num = 0, i = 0;
   for (i = 0; i < 5; i++) {
      printf("%d", num++);
   }
   return 0;
}

Output : [ 0 1 2 3 4 ]

Inside printf function we have used post increment operator. It will print the value of variable first and then it will increment the value of variable after execution of printf statement.

3.Post Increment Verity No 3

for(k=0;k<5;k++)
  {
  j = i++ + temp;
  printf("%d",j);
  }

Firstly old value of ‘i’ is added with temp and result of addition is assigned to ‘j’. After addition value of ‘i’ will be incremented

4.Post Increment Verity No 4

for(k=0;k<5;k++)
  {
  j = i++ < temp;
  printf("%d\n",j);
  }

Re-commanded Article : Conditional Operator in Expression

Firstly old value of ‘i’ is compared with ‘temp’ . Then result is assigned to j, and new value is used in second iteration.

5.Post Increment Verity No 5

for(k=0;k<5;k++)
  {
  j = i++;
  printf("%d",i);
  }
  • Old value of ‘i gets reflected only within same expression
  • In the above snippet Old value is assigned to ‘j’ . but in the next statement always ‘new value’ is used.
  • So while printing i Output will be = [1 2 3 4 5].

6.Post Increment Verity No 6

for(k=0;k<5;k++)
  {
  i = i++;
  printf("%d",i);
  }
  • Old value of ‘i is assigned to ‘i’ itself.
  • And again value is incremented after assigning.
  • So while printing i Output will be = [1 2 3 4 5].
  • But this Type is not supported by many compiles .

Note :

  1. Same things happens while using Post-Decrement.
  2. Post Increment is Unary Operator.
  3. Post-Increment Operator has Highest Priority

Conditional and assignment operator in expression

In this example we will be learning how to use conditional and assignment operator in single expression. In previous chapters we have learnt indirect use of if statement in expression

Use of conditional and assignment operator in expression

Consider below example where we have used the conditional and assignment operator in an expression.

#include <stdio.h>
int main(int argc, char *argv[]) {
   int a = 40, b = 30, c;
   c = !a <= !(c = b);
   printf("%d", c);
   return 0;
}

Output :

1

Explanation

Below is the explanation of the complex expression containing conditional and assignment operators -

conditional and assignment operator in expression

Step 1 : Solve the bracket first

While solving an expression, it is thumb rule to solve the bracket first. Lets see how we are solving the brackets -

c = !a <= !(c = b);
c = !a <= !(Assign Value of b to c);
c = !a <= !(30);

so at the end of step 1 our expression will be modified into following expression

c = !a <= !30;

We have replaced the expression (c=b) with 30 in original expression

Step 2 : List our operators with precedence

Now we need to arrange all the operators in the decreasing order of precedence. We are having 2 unary operators, 1 assignment and 1 conditional operator

Re-commanded Article : Operator Precedence and Priority

After listing out all the operators in descending order of priority -

NoOperator NamePriority
1Unary Not OperatorPriority 1
2Unary Not OperatorPriority 2
3Less than or equal toPriority 3
4Assignment OperatorPriority 4

"Not" Operator has higher priority than <= Operator. so we can write it as -

c = !a= !40 = 0

Replace !a by "0" as we calculated it in the above expression statement.

c = 0<=!30

Step 3 : Solve expression recursively

Now again we find there are 3 operators i.e equal to, greater than equal to and Not operator.

"Not" Operator has Higher Priority than any other priority specified in the expression

!30 = 0

so after replacing the expression will be like this -

c = 0 <= 0

Now when we try to solve then we find less than or equal to operator will get higher priority and obviously 0 <= 0 is True condition so it returns 1

c = 1

Relational operators in an expression : C Programming

In this tutorial we are going to see how we can use relational operators in an expression.

Relational operators in an expression

First of all we are going to list out the different relational operators.


Operator,Name of Operator
>,Greater Than
<,Less Than >=,Greater than Operator
<=,Less than Operator ==,Comparison Operator !=,Not equal to Operator [/table]

Use of relational operators in an expression is nothing but using if statement in an expression indirectly

Reading expression containing relational operators

If we use any of the operator listed in above table in your expression then that part of expression will provide you either 0 or 1 as a result. Consider below example -

res = 100 > 20

above expression will assign value 1 to a variable res because relational operators in an expression is used. Consider below example -

Thumb rules for solving expression

Keep in mind simple 2 thumb rules when you find relational operators in an expression -

  1. Check whether the expression is true or false. If expression is true then simply replace the expression with 1
  2. If expression results into false statement then replace the expression with 0

Examples

Example #1 : Usage of relational operator

#include <stdio.h>
int main(int argc, char *argv[]) {
   int num1 = 100;
   int num2 = 100;
   printf("%d",num1 >  num2);
   printf("%d",num1 >= num2);
   printf("%d",num1 <= num2);
   printf("%d",num1 <  num2);
   return 0;
}

Output :

0 1 1 0

You can see, we have used the relational operators inside the expression and it returns the result with values either 0 or 1. Operation is similar to below statement -

if(num1 > num2)
   printf("1");
else
   printf("0");

Example #2 : Indirect use of if statement

#include<stdio.h>
void main()
{
  int num1 = 100,num2=200,num3;
  num3 = ( num1 >= 100 ) + (num2 < 50 );
  printf("%d",num3);
}

Output :

1

Explanation :

Consider this statement -

num3 = ( num1 >= 100 );

above statement can be written in following way -

if( num1 >= 100 )    
   num3 = 1;
else    
   num3 = 0;

considering above thumb rules we can calculate the value of num3 as -

num3 = ( num1 >= 100 ) + (num2 < 50 );
num3 = 1 + (num2 < 50 );  // ( num1 >= 100 ) is True
num3 = 1 + 0;             // ( num2 <  50  ) is False
num3 = 1;

R-Value of Expression : C Programming

In the previous chapter we have learnt about the Lvalue of an expression in this chapter we are going to learn R-Value of Expression.

What is R-Value of Expression ?

  1. R Value stands for Right value of the expression.
  2. In any Assignment statement R-Value of Expression must be anything which is capable of returning Constant Expression or Constant Value.
  3. R Value Can be anything of following -
Examples of R-Value of Expression
VariableConstant
FunctionMacro
Enum ConstantAny other data type

Diagram Showing Lvalue :

Example of R-Value of Expression

#include<stdio.h>
int main()
{
int num;
num = 5;
return(0);
}

In the above example, Constant Value 5 is assigned to the variable will be considered as right Value of the variable.

Tips : R-Value of Expression

Tip 1 : R value may be constant or constant expression

num = 20;      //Constant RValue
num = 20 + 20; //Constant Expression as RValue
  1. In the example, we have assigned constant value to the variable.
  2. Constant value “20” is considered as RValue.
  3. In the next line we have assigned constant expression to the variable. “20 + 20” will be evaluated first and then result of expression will be assigned to an Variable.

Tip 2 : R value may be MACRO

#define MAX 20
main() {
   int num = MAX;
}

If we have defined a MACRO then we can use MACRO as right value. In the above example we have assigned the 20 to the variable “num”.

In case if we defined the MACRO value of different data type then it may results into compile error.

Tip 3 : R Value may be variable

#define MAX 20
main() 
{
   int flag = 0;
   int num  = flag;
}

For more information , Visit MSDN library.

L-Value of Expression : C Programming

In the previous chapter we have learnt about C Programming Expressions, in this chapter we will be learning about L-Value of Expression.

What is L-Value of Expression ?

  1. L-Value stands for left value
  2. L-Value of Expressions refer to a memory locations
  3. In any assignment statement L-Value of Expression must be a container(i.e. must have ability to hold the data)
  4. Variable is the only container in C programming thus L Value must be any Variable.
  5. L Value Cannot be Constant,Function or any of the available data type in C

Diagram Showing L-Value of Expression :

Example of L-Value of Expression :

#include<stdio.h>
int main()
{
  int num;
  num = 5;
return(0);
}

In the above expression, Constant value 5 is being assigned to a variable ‘num’. Variable ‘num’ is called as storage region’s , ‘num’ can considered as LValue of an expression.

Re-commanded Concepts : Concept of Variables and Constants in C

Important Tips :

Below are some of the tips which are useful to make your concept about L-Value of Expression more clear.

Lvalue cannot be a Constant

int main()
{
int num;
5 = num;  //Error
return(0);
}

You cannot assign the value or any constant value to another constant value because meaning of constant is already defined and it cannot be modified.

Lvalue cannot be a Constant Variable

Even we cannot assign a value to a constant variable. Constant variable should not be used as L Value.

int main()
{
const num;
num = 20;  //Error
return(0);
}

Lvalue cannot be a MACRO

We know that macros gets expanded before processing source code by compiler. All the macros will be replaced by defined value using pre-processor before compiling program.

#define MAX 20
int main()
{
MAX = 20;  //Error
return(0);
}

pre-processor will replace all the occurances of macros and hand over modified source code to compiler. following code will be given to compiler after doing pre-processor task

#define MAX 20
int main()
{
20 = 20;
return(0);
}

Re-commanded Reading : Preprocessor macro

Lvalue cannot be a Enum Constant

enum {JAN,FEB,MARCH};
int main()
{
JAN = 20;  //Error
return(0);
}

Lvalue cannot be a Data Type

#define<stdio.h>
#define max 125
struct book{
  char *name;
  int  pages;
};
void main()
{
book = {"C Programming",100};
}

L-Value Require error ?

Causes of Error :

  1. Whenever we are trying to assign value to constant value
  2. Whenever we are trying to increment or decrement Constant Expression
  3. Inside if statement , if we try to write comparison operator as “= =” instead of “==”, then we will get this error.

Solution :

Solution to this problem is very simple -

  1. Always try to assign constant value to “Variable“.
  2. If you are using comparison operator then we don’t provide space in between operators.

In the next chapter we will be learning RValue of an expression which is also called as right value of an expression.

C Programming Expression

A. C Programming Expression :

  1. In programming, an expression is any legal combination of symbols that represents a value. [Definition from Webopedia]
  2. C Programming Provides its own rules of Expression, whether it is legal expression or illegal expression. For example, in the C language x+5 is a legal expression.
  3. Every expression consists of at least one operand and can have one or more operators.
  4. Operands are values and Operators are symbols that represent particular actions.

Valid C Programming Expression :

C Programming code gets compiled firstly before execution. In the different phases of compiler, c programming expression is checked for its validity.

ExpressionsValidity
a + bExpression is valid since it contain + operator which is binary operator
+ + a + bInvalid Expression

Priority and Expression :

In order to solve any expression we should have knowledge of C Programming Operators and their priorities.

Types of Expression :

In Programming, different verities of expressions are given to the compiler. Expressions can be classified on the basis of Position of Operators in an expression -

TypeExplanationExample
InfixExpression in which Operator is in between Operandsa + b
PrefixExpression in which Operator is written before Operands + a b
PostfixExpression in which Operator is written after Operandsa b +

These expressions are solved using the stack.

Examples of Expression :

Now we will be looking into some of the C Programming Expressions, Expression can be created by combining the operators and operands

Each of the expression results into the some resultant output value. Consider few expressions in below table

Expression Examples,Explanation
n1 + n2,This is an expression which is going to add two numbers and we can assign the result of addition to another variable.
x = y,This is an expression which assigns the value of right hand side operand to left side variable
v = u + a * t,We are multiplying two numbers and result is added to ‘u’ and total result is assigned to v
x <= y,This expression will return Boolean value because comparison operator will give us output either true or false ++j,This is expression having pre increment operator\, it is used to increment the value of j before using it in expression [/table]

C Programming operator precedence & associativity

C Programming supports wide range of operators. While Solving the Expression we must follow some rules

While solving the expression [ a + b *c ] , we should first perform Multiplication Operation and then Addition, similarly in order to solve such complicated expression you should have hands on Operator Precedence and Associativity of Operators.

Operator precedence & associativity table

Operator precedence & associativity are listed in the following table and this table is summarized in decreasing Order of priority i.e topmost operator has highest priority and bottommost operator has Lowest Priority.

Operator

Description

Associativity

( )
[ ]

.
->
++ –

Parentheses (function call) (see Note 1)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement (see Note 2)

left-to-right

++ –
+ -
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (convert value to temporary value of type)
Dereference
Address (of operand)
Determine size in bytes on this implementation
right-to-left
*  /  %Multiplication/division/modulusleft-to-right
+  -Addition/subtractionleft-to-right
<<  >>Bitwise shift left, Bitwise shift rightleft-to-right
<  <=
>  >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
left-to-right
==  !=Relational is equal to/is not equal toleft-to-right
&Bitwise ANDleft-to-right
^Bitwise exclusive ORleft-to-right
|Bitwise inclusive ORleft-to-right
&&Logical ANDleft-to-right
| |Logical ORleft-to-right
? :Ternary conditionalright-to-left
=
+=  -=
*=  /=
%=  &=
^=  |=
<<=  >>=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
right-to-left

,

Comma (separate expressions)left-to-right

Summary of operator precedence

  1. Comma Operator Has Lowest Precedence .
  2. Unary Operators are Operators having Highest Precedence.
  3. Sizeof is Operator not Function .
  4. Operators sharing Common Block in the Above Table have Equal Priority or Precedence .
  5. While Solving Expression , Equal Priority Operators are handled on the basis of FIFO [ First in First Out ] i.e Operator Coming First is handled First.

Important definitions

Unary OperatorA unary operation is an operation with only one operand, i.e. an operation with a single input .

A unary operator is one which has only one operand. e.g. post / pre increment operator

Binary OperatorA Binary operator is one which has two operand. e.g. plus , Minus .
AssociativityTheir associativity indicates in what order operators of equal precedence in an expression are applied
Precedence Priority Of Operator

Examples : operator precedence & associativity

We have listed out some of the examples based on operator precedence & associativity. Examples will give you clear picture how to use operator precedence & associativity table chart while solving the expression

Example 1 : Simple use of precedence chart

#include<stdio.h>
int main() {
  int num1 = 10, num2 = 20;
  int result;
  result = num1 * 2 + num2;
  printf("\nResult is : %d", result);
  return (0);
}

consider the simple expression used in above program and refer operator precedence & associativity table chart

result = num1 * 2 + num2;

In this case multiplication operator will have higher priority than addition and assignment operator so multiplication will be evaluated firstly.

result = num1 * 2 + num2;
result = 10 * 2 + 20;
result = 20 + 20;
result = 40;

Example 2 : Use of associativity

In above example none of the operator has equal priority. In the below example some operators are having same priority.

result = num1 * 2 + num2 * 2 ;

In the above expression we have overall 3 operators i.e. 2 multiplication, 1 addition and 1 assignment operator.

Now refer operator precedence & associativity table (block 3) which clearly tells that associativity is from left to right so we will give priority to multiplication operator on the left side

result = num1 * 2 + num2 * 2 ;
result = 10 * 2 + 20 * 2 ;
result = 20 + 20 * 2 ;
result = 20 + 40 ;
result = 60 ;