+ 7
please give the output along with explanation.
#include <stdio.h> int r() { static int n=7; return n--; } int main() { for(r();r();r()) printf("%d",r()); return 0;
1 ответ
+ 4
The output is 52.
The code can be reformatted like this:
#include <stdio.h>
int r()
{
static int n = 7;
return n--;
}
int main()
{
for(r(); r(); r())
printf("%d", r());
return 0;
}
Note the indentation of the printf, since the first statement after a for loop without a block will be part of the for loop.
In C, a static variable means that the variable is not freed at the end of the block, it instead stays in memory. Because of this behavior, the first time r is called, it will be 7 (postfix -- returns value before decrementing), the next time it will be 6, then 5, then 4, and so on.
Using this information, the for loop will start with the initialization statement (r()), which decrements n (n is now 6) and returns 7. The condition (second) part of the for loop is also r(), so when called it will return 6 (n is now 5), which isn't 0, so it is true meaning the loop will run. Inside of the body of the for loop, r() (r currently returns 5) is printed, and n is now 4.
After the first iteration of the loop is done, the increment statement of the for loop (r()) will be run. This returns 4, and n is now 3. Next the condition will be ran, which will result in 3, with n now being 2. Since 3 is still not 0, the printf call will run, and output 2, with n now being 1.
After this iteration, the increment statement will be called again, resulting in 1, n is now 0. The condition will now run with r returning 0, which is false. This stops the loop and main will exit with 0.
Here is a breakdown (* means that the variable is not necessary for the current stage):
First iteration:
n = 7
for (7; 6; *)
printf("%d", 5);
Increment:
for (*; *; 4)
printf("%d", *);
Second iteration:
n = 3
for (*; 3; *)
printf("%d", 2);
Increment:
for (*; *; 1)
printf("%d", *);
Final iteration:
n = 0
for (*; 0; *)
printf("%d", *);
// 0 represents false, ending the loop
Final result: 52