Coroutines in C/C++


In this tutorial, we will be discussing a program to understand coroutines in C/C++.

Coroutines are control instructions which switch the execution control between two routines which returning any of them.

Example

 Live Demo

#include<stdio.h>
int range(int a, int b){
   static long long int i;
   static int state = 0;
   switch (state){
   case 0:
      state = 1;
      for (i = a; i < b; i++){
         return i;
      //returning control
      case 1:; //resuming control
      }
   }
   state = 0;
   return 0;
}
int main(){
   int i;
   for (; i=range(1, 5);)
      printf("control at main :%d\n", i);
   return 0;
}

Output

control at main :1
control at main :2
control at main :3
control at main :4

Updated on: 16-Mar-2020

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements