1、
#include <stdlib.h>
#include <stdio.h>
void
Fun_Exit(void)
{
exit(1);
}
int
Fun_Test(int n)
{
if (n > 0) {
Fun_Exit();
printf("Hello World\r\n");
} else
return 0;
}
int
main(int argc, char *argv[])
{
return 0;
}
编译结果如下:
结果:编译器警告,说返回值非空的函数Fun_Test()少了一个返回值。
2、
#include <stdlib.h>
#include <stdio.h>
void
Fun_Exit(void)
{
exit(1);
}
int
Fun_Test(int n)
{
if (n > 0) {
Fun_Exit();
printf("Hello World\r\n");
return 1;
} else
return 0;
}
int
main(int argc, char *argv[])
{
return 0;
}
编译结果如下图:
结果:0个错误,0个警告。
3、
#include <stdlib.h>
#include <stdio.h>
void __attribute__((noreturn)) Fun_Exit(void)
{
exit(1);
}
int
Fun_Test(int n)
{
if (n > 0) {
Fun_Exit();
printf("Hello World\r\n");
return 1;
} else
return 0;
}
int
main(int argc, char *argv[])
{
return 0;
}
编译结果如下图:
结果:0个错误 0个警告。
总结:
编译器发出警告Fun_Test函数应该有一个返回值,但是当 n > 0 时,编译器却无法找到返回值。如果在 printf() 函数后面添加一行 return 1; 那么编译时警告消失。尽管 Fun_Exit() 调用的是 exit() 函数,且实际上程序在 n > 0 时也不会到达 printf() 函数,但编译器不会去检查 Fun_Exit() 函数体是什么,它认为Fun_Exit() 后,程序会继续执行。然而,我们可以在Fun_Exit() 的前面添加 __attribute__((noreturn))后,那么在不用添加 return 1语句的情况下,编译器也不会发出警告,因为 noreturn 属性明确告诉编译器:“ 到我这里,就不会返回了,你无需再发出警告”。