jeudi 23 juillet 2020

Flow of execution of an if-else-if construct in C

Here's the code for which I'm confused about how it is executing itself:-

1.  #include <stdio.h>
2. 
3.  int main()
4.  {
5.    int a = 2, b = 3;
6.    if(a == 1)
7.     printf("a: 1\n");
8.    else if(a == 2 || a == 3)
9.    {
10.     if(b == 3)
11.       printf("b: 3\n");
12.     else
13.       printf("---\n");
14.   }
15.   else
16.    printf("final else\n");
17.   return 0;
18.  }

I put a breakpoint at line no. 5 then using gdb executed this program line by line. As expected, it(line selector) entered into the else if block then inside if(b == 3) block and executed the line no. 11 outputting it onto the console then it went back to line no. 10 executed it then it executed line no. 17 and so on.

But as I know if any if block is executed it should directly go and continue the execution from the statement following its if-else block. Means in the above program after executing if(b == 3) block program execution should directly go to the line no. 17 and continue execution. But this is not what is happening here. Why?

One more thing( if it is necessary), if replace else if(a == 2 || a == 3) with else if(a == 2). Program executes itself as expected, means after executing line no. 11 it goes right to the line no. 17 and continues executing itself.

Aucun commentaire:

Enregistrer un commentaire