如何将函数参数标记为输出

Dan*_*ski 3 c c++ attributes gcc out

C#允许将函数参数标记为仅输出:

void func(out int i)
{
    i = 44;
}
Run Code Online (Sandbox Code Playgroud)

是否有可能在C/C++中做类似的事情?这可以改善优化.另外应该使警告静音"错误:'myVar'可以在此函数中未初始化使用",当变量未初始化然后传递给函数作为输出参数时.

我使用gcc/g ++(目前是4.4.7)来编译我的代码.

编辑:我知道指针和引用,这不是我要找的.我需要这样的东西:

void func(int* __attribute__((out)) i)
{
    *i = 44;
}

void func2()
{
    int myVal; // gcc will print warning: 'myVar' may be used uninitialized in this function
    func(&myVal);
    //...
}
Run Code Online (Sandbox Code Playgroud)

编辑2:需要一些额外的代码来重现警告"'myVar'可能在此函数中未初始化使用".另外,你必须将-Wall -O1传递给gcc.

void __attribute__((const)) func(int* i)
{
    *i = 44;
}

int func2()
{
    int myVal; // warning here
    func(&myVal);
    return myVal;
}
Run Code Online (Sandbox Code Playgroud)

πάν*_*ῥεῖ 7

"在C/C++中可以做类似的事情吗?"

并不是的.标准c ++或c不支持仅输出参数之类的东西.

在c ++中,您可以使用引用参数来获取/输出语义:

void func(int& i) {
          // ^
    i = 44;
}
Run Code Online (Sandbox Code Playgroud)

对于c你需要一个指针,做同样的事情:

void func(int* i) {
          // ^ 
    *i = 44;
 // ^
}
Run Code Online (Sandbox Code Playgroud)

请注意,除了使用引用(仅表示输入)之外out,in&out参数之间没有区别const:

void func(const int& i) {
       // ^^^^^
    i = 44;
}
Run Code Online (Sandbox Code Playgroud)