C#允许将函数参数标记为仅输出:
void func(out int i)
{
i = 44;
}
在C/C++中是否有类似的方法?这可以改善优化。此外,当变量未初始化并作为输出参数传递到函数时,“error:'myVar' may be used uninitialized in this function”警告应该被忽略。
我使用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);
//...
}
编辑2:需要添加一些额外的代码才能重现警告“'myVar'在此函数中可能未初始化”。此外,您需要将-Wall -O1传递给gcc。
void __attribute__((const)) func(int* i)
{
*i = 44;
}
int func2()
{
int myVal; // warning here
func(&myVal);
return myVal;
}
__attribute__((const))
欺骗编译器,承诺该函数“除了返回值之外不会检查任何值,也没有其他影响”(https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html),现在你抱怨编译器被欺骗了? - T.C.