Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 写函数内联(非内联函数)C/C++;_C++_C_Function_Inline - Fatal编程技术网

C++ 写函数内联(非内联函数)C/C++;

C++ 写函数内联(非内联函数)C/C++;,c++,c,function,inline,C++,C,Function,Inline,我想知道我是否可以写一些类似内联函数的东西,或者更像是带有返回语句的块。下面是我思考的一个例子: int main(int argc, char* argv[]) { printf("result is '%s'\n", { char buffer[100]; //Do some code here to determine string return buffer; } )

我想知道我是否可以写一些类似内联函数的东西,或者更像是带有返回语句的块。下面是我思考的一个例子:

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函数是从C++11开始引入的,因此您应该有一个兼容的编译器(现在几乎所有最近的编译器都支持它们)

这只是一个小例子:

#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;
}
#包括
#包括
int main(int argc,char*argv[]){
//定义闭包-注意使用“自动”自动确定类型。
自动我的λ=[]()->std::string{
返回std::string(“这是一个字符串”);
};

GCC支持嵌套函数作为扩展,但它不是可移植/标准的


或者,您可以使用lambda。

标准的C解决方案是编写过程代码,而不是“功能”代码:

您可以使用
{/*…*/}
引入嵌套作用域,甚至在函数内部

请注意,您显示的代码(即使有类似lambdas的代码)会导致未定义的行为,因为您返回的指针指向不再存在的数组(它已超出范围)


如果那个<代码> /一些代码…<代码>是很多的,那么你把它放在一个单独的函数中,并把它标记为“代码>静态< /代码>,使它不从翻译单元导出。

看起来你想要一个选择C或C++。这些是不同的语言,不同的解决方案。@ BaummitAugen,好像我们已经有C++的解决方案,从N开始。AthoLover如果C有一个,那也不错。@ JohnLeuenhagen是一个不同的问题,因为C不是C++不是C。为什么要这样?为什么不使用内联函数?
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;
}