0

How this program executes?

#include <stdio.h> #include <string.h> int f(int n){ static int i=1; return n+i--; } int main() { char ch[]="CODE"; int n = strlen(ch), i=0; for(f(n);i=f(n);i++) printf("%s\n",ch+i-1); return 0; }

23rd Nov 2024, 7:03 PM
Muskan Ali Qureshi
Muskan Ali Qureshi - avatar
3 Respuestas
+ 5
Go to create tab in the code section tap + button and paste the code and click run.
23rd Nov 2024, 7:22 PM
Aysha
Aysha - avatar
+ 3
cryptic codes are good for puzzles, but I hope you're not planning on using this on practical projects. it's the same as #include <stdio.h> #include <string.h> int main(){ char ch[]="CODE"; for(int i=strlen(ch);i>0;i--) printf("%s\n",ch+i-1); } only more complicated. You can put printf inside the f function to see what's going on when the program runs. The int i inside the function f is declared static, meaning it will retain its value and will not be reset between function calls. So it becomes more and more negative each time (i--) which makes returned value smaller and smaller (n+i--) every time f(n) is called.
24th Nov 2024, 4:31 AM
Bob_Li
Bob_Li - avatar
0
maybe I've made it more complicated than necessary, but here is how you can see the values in each part of the code as the for loop runs #include <stdio.h> #include <string.h> int f(int n){ static int i=1; printf(" inside f(n) i = %d\n", i); int returnval = n+i--; printf(" n+i-- = %d\n", returnval); return returnval; } int main(){ char ch[]="CODE"; int n = strlen(ch), i=0; for(f(n);(i=f(n));i++){ printf(" in main() i = %d\n", i); printf("\nch+i-1 = ch+%d = %s\n\n", i-1, ch+i-1); } printf("\nmain i = f(n) = %d\n", i); return 0; }
24th Nov 2024, 1:47 PM
Bob_Li
Bob_Li - avatar