Consider the following C program:
- #include <stdio.h>
- int r() {
- static int num=7;
- return num--;
- }
- int main() {
- for (r();r();r())
- printf(“%d”,r());
- return 0;
- }
Which one of the following values will be displayed on execution of the programs?
GATE CSE 2019Programming in C › General C Programming ConceptsVerified
(B) 52 52 52
Trace the static variable num through each call to r(), remembering that post-decrement returns the current value before decrementing. Evaluate the for-loop parts in C order: initialization once, condition before each iteration, body when condition is true, then increment expression.
Post-decrement returns the old value and then decrements the static variable. Tracing the for-loop: r() before the loop returns 7 and leaves num=6; the first condition returns 6 and leaves num=5, so the body prints 5; the increment returns 4 and leaves num=3; the second condition returns 3 and leaves num=2, so the body prints 2; the next increment returns 1 and leaves num=0; the final condition returns 0 and terminates the loop. Hence the displayed value is 52.
Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.