Saturday, February 3, 2018

Coding using keywords- part 4 (goto)

Before starting, you can see all the keywords in C here: https://philippebalech.blogspot.com/2018/01/keywords-in-c.html

A goto statement is used to jump unconditionally from the goto label statement to a labeled statement in the same function.



Let's take an example on it.


  1. #include <stdio.h>  
  2.    
  3. int main () {  
  4.   
  5.    /* local variable definition */  
  6.    int a = 10;  
  7.   
  8.    /* do loop execution */  
  9.    LOOP:do {  
  10.      
  11.       if( a == 15) {  
  12.          /* skip the iteration */  
  13.          a = a + 1;  
  14.          goto LOOP;  
  15.       }  
  16.           
  17.       printf("value of a: %d\n", a);  
  18.       a++;  
  19.   
  20.    }while( a < 20 );  
  21.    
  22.    return 0;  
  23. }  

The output will be as follows:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19


Explanation

Inside the while loop a with initial value of 10 will be incremented till 19 the last value before 20. Inside the while block there's an if that when a reaches 15 goto will go back to LOOP after incrementing a one time. For this reason the number 15 will be skipped.

No comments:

Post a Comment