“Control reaches end of non-void function after switch case statement.”

huangapple go评论86阅读模式
英文:

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 &lt;cassert&gt;

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

答案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.

huangapple
  • 本文由 发表于 2023年8月4日 22:15:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定