Adding or subtracting 1 is so common that C has special operators for it. They are short and convenient, but their prefix and postfix forms behave differently inside larger expressions, and using them carelessly can make a program’s behaviour undefined.
Prefix and postfix forms
The increment operator ++ adds 1 to a variable; the decrement operator -- subtracts 1.
Expression
Effect on a
Value used in the expression
++a (pre-increment)
a becomes a + 1
The new value
a++ (post-increment)
a becomes a + 1
The old value
--a (pre-decrement)
a becomes a - 1
The new value
a-- (post-decrement)
a becomes a - 1
The old value
Used alone as a statement, a++;, ++a; and a = a + 1; all have the same effect. The difference appears only when the value is used in a larger expression.
Undefined behaviour: changing a variable twice
If an expression modifies a variable more than once, or modifies it and also reads it elsewhere in the same expression, the C standard does not define the result. Different compilers, or the same compiler with different settings, may give different answers. This is called undefined behaviour.
C · unsafe.c
#include <stdio.h>int main(void){ int a = 1, b = 2, c = 3, k; k = (a++) * (++b) + ++a - --c; /* a is modified twice */ printf("a=%d b=%d c=%d k=%d\n", a, b, c, k); return 0;}
Compiler output
gcc: warning: operation on 'a' may be undefined [-Wsequence-point]clang: warning: multiple unsequenced modifications to 'a' [-Wunsequenced]
Output (gcc 13 and clang 18, x86-64)
a=3 b=3 c=2 k=4
Safe rule: in one expression, apply ++ or -- to a variable at most once, and do not use that variable anywhere else in the same expression.
Key takeaways
++ adds 1 and -- subtracts 1; both are unary.
Prefix uses the new value; postfix uses the old value.
Alone as statements, a++, ++a and a = a + 1 are equivalent.
Modifying a variable twice in one expression is undefined behaviour; compilers warn about it.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Trace int p = 3, q = 8, r; r = p++ * 2 + --q; and give the final values of p, q and r.
Show worked answer
p++ contributes the old value 3 and then p becomes 4. --q decrements q to 7 and contributes 7. So r = 3 * 2 + 7 = 6 + 7 = 13. Final values: p = 4, q = 7, r = 13. Each variable is modified only once, so the result is well defined.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-types-operators-and-expressions/increment-and-decrement-operators/ to read this page.