我不认为这是重复的,因为该函数的确返回了快乐路径。使用该属性no-return
可使编译器在该函数永不返回的假设下进行优化,此处并非如此。
我有C代码,它要么返回指针,要么调用另一个函数退出程序。这是在if
语句中,因此它要么返回结果,要么退出。当函数返回a时void *
,编译器警告该函数可能不会返回值(这当然是对的):
error: control reaches end of non-void function [-Werror=return-type]
我可以通过仅添加return *temp;
到函数的末尾来解决此问题,但是我想通过使用未使用的变量属性之类的东西来弄清楚我的意图:
__attribute__((__unused__))
这样,我可以-Wall
继续使用,而不必添加不必要的或可能引起混淆的代码。
如果有更好的方式表达这种意图,我也愿意重写代码。
该代码如下所示:
void *get_memory() {
void *temp = malloc(100);
if (temp) {
// do some setup work
return temp;
} else {
exit_program_with_epic_fail();
}
// Compiler warns if the following line isn't present
return temp;
}
Run Code Online (Sandbox Code Playgroud)
有两种方法可以消除警告:
exit_program_with_epic_fail()
适当的属性标记函数_Noreturn
,但对于 C11 之前的编译器没有可移植的方法来执行此操作。许多编译器都支持__attribute__((noreturn))
,特别是gcc、clang和tinycc,但它是编译器特定的扩展。这是修改后的版本:
void *get_memory(void) {
void *temp = malloc(100);
if (!temp) {
exit_program_with_epic_fail();
}
// do some setup work
return temp;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
102 次 |
最近记录: |