C# 允许将函数参数标记为仅输出:
void func(out int i)
{
i = 44;
}
是否可以在 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);
//...
}
编辑2:需要一些额外的代码来重现警告“'myVar'可能在此函数中未初始化地使用”。此外,您必须将 -Wall -O1 传递给 gcc。
void __attribute__((const)) func(int* i)
{
*i = 44;
}
int func2()
{
int myVal; // warning here
func(&myVal);
return myVal;
}
“是否可以在 C/C++ 中做类似的事情?”
其实不然。标准 c++ 或 c 不支持诸如仅输出参数之类的东西。
在 C++ 中,您可以使用引用参数来获取输入/输出语义:
void func(int& i) {
// ^
i = 44;
}
对于 c 你需要一个指针,来做同样的事情:
void func(int* i) {
// ^
*i = 44;
// ^
}
请注意,
out
和 in&out
参数之间没有区别,除非您使用 const
引用(仅表示输入):
void func(const int& i) {
// ^^^^^
i = 44;
}
当您想在 C++ 中传递 arg 作为输出时,您可以将其作为引用传递:
void func(int &i)
{
i = 44;
}
并且您必须在对其执行任何操作之前初始化它。
注意: 您可以指定何时希望 arg 只是带有 const ref 的 input :
void func(const int &i)
{
i = 44;
}
正如其他人所指出的,您可以使用指针或引用来传递参数。但是没有办法注释它是in、out还是in/out。
void func(int &i); // Out or in/out. Non-nullable.
void func(int *i); // Out or in/out. Nullable.
void func(const int &i); // In. Non-nullable.
void func(const int *i); // In. Nullable.
Microsoft 编译器扩展
如果使用 MSVC,Microsoft 源代码注释语言 (SAL) 可以提供此类注释并执行编译时静态分析以强制调用者正确使用。
void func(_Out_ int &i);
void func(_Out_ int *i);
void func(_Out_opt_ int *i);
void func(_Inout_ int &i);
void func(_Inout_ int *i);
void func(_Inout_opt_ int *i);
void func(_In_ const int &i);
void func(_In_ const int *i);
void func(_In_opt_ const int *i);