Advertisement
zmatt

gcc-nested-functions.c

Aug 22nd, 2018
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.72 KB | None | 0 0
  1. #include <stddef.h>
  2. #include <stdbool.h>
  3. #include <stdio.h>
  4.  
  5. void call_for_each( void (*fun)( int ), int start, int end )
  6. {
  7.     for( int i = start; i < end; i++ )
  8.         fun( i );
  9. }
  10.  
  11. bool contains( int const values[], size_t count, int match )
  12. {
  13.     __label__ found;
  14.  
  15.     // note: only supported by gcc, not by g++ or clang
  16.     void check( int index ) {
  17.         if( values[ index ] == match )
  18.             goto found;
  19.     }
  20.  
  21.     call_for_each( check, 0, count );
  22.     return false;
  23. found:
  24.     return true;
  25. }
  26.  
  27. int main()
  28. {
  29.     int const values[] = { 2, 5, 7 };
  30.     size_t const count = sizeof(values) / sizeof(int);
  31.  
  32.     for( int i = 0; i < 8; i++ ) {
  33.         printf( "contains %d: %s\n", i,
  34.             contains( values, count, i ) ? "yes" : "no" );
  35.     }
  36.  
  37.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement