英文:
Control reaches end of non void function after switch case statement
问题
我有一段代码,其中我对枚举类的所有值执行了一个switch case语句。所有分支都有return语句,但gcc(至少10.5和trunk版本)仍然认为控制可能会到达函数的结尾。相同的代码在clang 16中编译正常。
这是正确的还是gcc中的一个bug?
#include <cassert>
enum class C
{
A, B
};
int foo()
{
C c;
switch (c) {
case C::A:
assert(false);
case C::B:
return 0;
}
}
https://godbolt.org/z/v3K6jx5aG
英文:
I have a piece of code where I do a switch case statement for all the values of an enum class. All the branches have a return statement, but the gcc (at leat 10.5 and trunk) still thinks that the control can reach the end of the function. Same code compiles fine with clang 16.
Is this correct or a bug in gcc?
#include <cassert>
enum class C
{
A, B
};
int foo()
{
C c;
switch (c) {
case C::A:
assert(false);
case C::B:
return 0;
}
}
答案1
得分: 5
This is correct.
enum
is an int
(or another integral type), it can store any integer. An uninitialized enum c
can have any value, also different from all enumerator list elements.
Note that your code is incorrect. The sole act of reading the uninitialized value of c
inside switch (c)
is making your code have technically undefined behavior.
Producing, or not, a warning about reading an uninitialized value or about a control flow potentially reaching the end of a non-void function is up to the good will of the compiler, it is not something required. It is a quality of implementation issue.
英文:
> Is this correct or a bug in gcc?
This is correct.
enum
is an int
(or another integral type), it can store any integer. An uninitialized enum c
can have like any value, also different from all enumerator list elements.
Note that your code is incorrect. The sole act of reading the uninitialized value of c
inside switch (c)
is making your code have technically undefined behavior.
Producing, or not, a warning about reading an uninitialized value or about a control flow potentially reaching the end of a non-void function is up to the good will of the compiler, it is not something required. It is a quality of implementation issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论