[英]How to pass a block of code in curly brackets to a function in C?
Something like就像是
int main(void){
doTenTimes({
printf("Hello World");
});
}
And then the function doTenTimes could execute that block of code 10 times.然后 function doTenTimes 可以执行该代码块 10 次。
You probably don't want to "pass a block of code", but rather to implement the function to suit whatever you need to do:您可能不想“传递代码块”,而是实现 function 以适应您需要做的任何事情:
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:或者,您可以传递指向不同 function 的 function 指针,以单独提供行为:
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);
You really can't treat "naked" blocks of code like data in C.你真的不能像 C 中的数据一样对待“裸”代码块。 Lundin's approach is the best for what you want to do.
Lundin 的方法最适合您想做的事情。
However, for completeness' sake, here's an example using a macro ( FOR THE LOVE OF GOD NEVER DO THIS ):但是,为了完整起见,这里有一个使用宏的示例( 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.
永远不要做这样的事情。
#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请参阅在https://ideone.com/ivsxxR上运行的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.