Skip to study material
← Question index

QUESTION 63 · Operators

Differentiate ++x and x++ when their expression value is used.

2 marks

Answer

Prefix ++x gives the updated value; postfix x++ gives the previous value. Both increment x by one.

  • Starting separately with x = 5, y = ++x; leaves y = 6 and x = 6.
  • Starting separately with x = 5, y = x++; leaves y = 5 and x = 6.

QUESTION 64 · Operators

Differentiate prefix and postfix increment and decrement operators.

5 marks

Answer in brief

The increment operator ++ increases a variable by one. The decrement operator -- decreases it by one. Each has a prefix and a postfix form.

Prefix form

The operator is placed before the variable: ++x or --x. The expression gives the updated value. Starting with x = 5, y = ++x; leaves both x and y equal to 6. Starting with x = 5, y = --x; leaves both equal to 4.

Postfix form

The operator is placed after the variable: x++ or x--. The expression gives the previous value while the variable is updated. Starting with x = 5, y = x++; leaves y equal to 5 and x equal to 6. Starting with x = 5, y = x--; leaves y equal to 5 and x equal to 4.

When used alone

As separate statements, ++x; and x++; both increase x by one. Their difference matters when the expression value is used, as in an assignment. The same rule applies to decrement.

Important points

  1. Writable variable: The operand must be something C permits to be changed. A constant such as 5 cannot be incremented.
  2. Valid range: The updated value must fit the type; signed overflow has no defined result.
  3. Separate changes: Do not use i++ + ++i. It changes i without the required ordering and has undefined behaviour, so there is no guaranteed answer.
  4. Clear code: Use separate statements when several updates would be confusing.

Reference table

↔ Scroll horizontally on a small screen
Start with x = 5 for each row
StatementValue assigned to yFinal x
y = ++x;66
y = x++;56
y = --x;44
y = x--;54

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int x = 5;
    int before = x++;
    int after = ++x;
    printf("before = %d\n", before);
    printf("after = %d\n", after);
    printf("x = %d\n", x);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

before = 5
after = 7
x = 7

Key points

  • Prefix and postfix differ when their expression value is used.
  • Use separate statements when sequencing matters.