What are the signs of crosses initialization?

后端 未结 4 1124
谎友^
谎友^ 2020-11-28 03:28

Consider the following code:

#include 
using namespace std;

int main()
{
    int x, y, i;
    cin >> x >> y >> i;
    swit         


        
4条回答
  •  悲&欢浪女
    2020-11-28 03:52

    The version with int r = x + y; won't compile either.

    The problem is that it is possible for r to come to scope without its initializer being executed. The code would compile fine if you removed the initializer completely (i.e. the line would read int r;).

    The best thing you can do is to limit the scope of the variable. That way you'll satisfy both the compiler and the reader.

    switch(i)
    {
    case 1:
        {
            int r = 1;
            cout << r;
        }
        break;
    case 2:
        {
            int r = x - y;
            cout << r;
        }
        break;
    };
    

    The Standard says (6.7/3):

    It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).

提交回复
热议问题