GCC/G++'s treatment of missing return statement

本文通过一个缺少返回语句的C函数示例,展示了GCC如何发出警告,并引用了C99标准的相关规定。此外,还对比了C++标准中的相应规则。
gcc will not complain the missing of return statement.

foo.c

int add(int l, int r) {
}
int main(int argc, const char *argv[]) {
int result = add(1, 2);
result++;
return 0;
}

$ gcc foo.c

By add -Wall, gcc gives a warning

$ gcc -Wall foo.c
foo.c: In function ‘add’:
foo.c:2: warning: control reaches end of non-void function

In 6.8.6.4 of C99 standaard, there is the following text:

A return statement with an expression shall not appear in a function whose
return type is void. A return statement without an expression shall only appear
in a function whose return type is void.

So gcc treats this constraint as a warning.

g++ is similar to gcc regarding return statement missing. In 7.3 of The C++
Programming Languge (3rd edition), there is the following text:

A value must be returned from a function that is not declared void (however,
main() is special; see void main §3.2). Conversely, a value cannot be returned
from a void function.

In 6.6.3 of ISO/IEC 14882:2003, there is the following text:

Flowing off the end of a function is equivalent to a return with no value; this
results in undefined behavior in a value-returning function.

http://old.nabble.com/missing-return-statement-td22487507.html is a discussion
about why g++ treats missing return statement in the current way.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值