写内联函数(不是内联函数)C/C++
Write function inline (not inline function) C/C++
我想知道我是否可以编写类似内联函数的东西,或者更像是带有 return 语句的块。这是我的想法的一个例子:
int main(int argc, char* argv[])
{
printf("result is '%s'\n",
{
char buffer[100];
//Do some code here to determine string
return buffer;
}
)
return 0;
}
您正在查找的是 lambda function。
注意自C++11以来引入了lambda函数,所以你应该有一个兼容的编译器(几乎所有最新的编译器现在支持他们)。
这只是一个小例子:
#include <string>
#include <iostream>
int main(int argc, char* argv[]) {
// Define a closure - note use 'auto' in order to auto-determine the type.
auto my_lambda = []() -> std::string {
return std::string("This is a string");
};
std::cout << "Result: " << my_lambda() << std::endl;
return 0;
}
附加说明:这是 C++。 C没有那种东西。
GCC 支持嵌套函数作为扩展,但不 portable/standard.
或者您可以使用 lambda。
标准的 C 解决方案是编写程序,而不是 "functional" 代码:
int main(int argc, char* argv[])
{
char buffer[100];
{
// some code, note that variables here go out of scope at the next }
}
printf("result is '%s'\n", buffer);
return 0;
}
您可以使用 { /* ... */ }
引入嵌套作用域,甚至在函数内部。
请注意,您显示的代码会 - 即使存在类似 lambdas 的东西 - 也会导致未定义的行为,因为您返回的是指向不再存在的数组的指针(它已超出范围)。
如果// some code ...
很多,那么你把它放在一个单独的函数中,并将其标记为static
,这样它就不会从翻译单元中导出。
我想知道我是否可以编写类似内联函数的东西,或者更像是带有 return 语句的块。这是我的想法的一个例子:
int main(int argc, char* argv[])
{
printf("result is '%s'\n",
{
char buffer[100];
//Do some code here to determine string
return buffer;
}
)
return 0;
}
您正在查找的是 lambda function。
注意自C++11以来引入了lambda函数,所以你应该有一个兼容的编译器(几乎所有最新的编译器现在支持他们)。
这只是一个小例子:
#include <string>
#include <iostream>
int main(int argc, char* argv[]) {
// Define a closure - note use 'auto' in order to auto-determine the type.
auto my_lambda = []() -> std::string {
return std::string("This is a string");
};
std::cout << "Result: " << my_lambda() << std::endl;
return 0;
}
附加说明:这是 C++。 C没有那种东西。
GCC 支持嵌套函数作为扩展,但不 portable/standard.
或者您可以使用 lambda。
标准的 C 解决方案是编写程序,而不是 "functional" 代码:
int main(int argc, char* argv[])
{
char buffer[100];
{
// some code, note that variables here go out of scope at the next }
}
printf("result is '%s'\n", buffer);
return 0;
}
您可以使用 { /* ... */ }
引入嵌套作用域,甚至在函数内部。
请注意,您显示的代码会 - 即使存在类似 lambdas 的东西 - 也会导致未定义的行为,因为您返回的是指向不再存在的数组的指针(它已超出范围)。
如果// some code ...
很多,那么你把它放在一个单独的函数中,并将其标记为static
,这样它就不会从翻译单元中导出。