Home > database >  How to pass a block of code in curly brackets to a function in C?
How to pass a block of code in curly brackets to a function in C?

Time:01-22

Something like

int main(void){
    doTenTimes({
        printf("Hello World");
    });
}

And then the function doTenTimes could execute that block of code 10 times.

CodePudding user response:

You probably don't want to "pass a block of code", but rather to implement the function to suit whatever you need to do:

void doManyTimes(int n)
{
  for(int i=0; i<n; i  )
    printf("Hello World\n");
}

Alternatively, you could pass a function pointer pointing at a different function, to provide the behavior separately:

typedef void dofunc_t (void);

void print (void)
{
  printf("Hello World\n");
}

void doManyTimes(dofunc_t* func, int n)
{
  for(int i=0; i<n; i  )
    func();
}

// call:
doManyTimes(print,10);

CodePudding user response:

You really can't treat "naked" blocks of code like data in C. Lundin's approach is the best for what you want to do.

However, for completeness' sake, here's an example using a macro (FOR THE LOVE OF GOD NEVER DO THIS):

#include <stdio.h>

/**
 * Wrapping in a do...while(0) keeps the compiler from bitching at
 * me over the trailing semicolon when I invoke the macro in main.
 */
#define doTenTimes(STMT) do { for (size_t i = 0; i < 10; i   ) STMT } while( 0 )

int main( void )
{
  doTenTimes( { printf( "hello, world\n" ); } );
  return 0;
}

After preprocessing we get this:

int main( void )
{
  do { for (size_t i = 0; i < 10; i   ) {printf( "hello, world\n" ); } } while (0);
  return 0;
}

It "works", but it's super ugly and made me itch as I wrote it. Don't ever do anything like this.

CodePudding user response:

#include <stdio.h>

void hello(void) {
    puts("Hello, World!");
}

void byebye(void) {
    puts("Good bye, World!");
}

int main(void) {
    void (*work)(void) = hello;
    for (int i = 0; i < 10; i  ) work();
    work = byebye;
    for (int i = 0; i < 10; i  ) work();
    return 0;
}

See code running at https://ideone.com/ivsxxR

  •  Tags:  
  • Related