S
S
sddvxd2018-12-20 22:49:28
C++ / C#
sddvxd, 2018-12-20 22:49:28

Why can't you initialize in a case?

Hello!

switch(1){
case 1:
    double d = 1; //ошибка
}

I found an explanation for this on an English-language site, but I could not fully understand the meaning. please explain why

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2018-12-21
@sddvxd


switch(1){
case 1:
    double d = 1; //ошибка
}

Why can't you initialize in a case?

With this code, everything is in order from the point of view of the standard. Problems start if we add case labels to the switch after the variable d has been defined. Jumping to these labels is included in the scope of the d variable, but bypasses its initialization. This is forbidden by the standard (c++98, 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.

V
Vasily Melnikov, 2018-12-21
@BacCM

This is from the crooked heritage of C most likely.
switch/case is akin to goto but not really
, so you can do all sorts of wild things with loops and ifs that overlap parts of the switch.
And in the end, what happens.
This code is quite valid:

int x = 1;
switch (x) {
  case 1:;
  case 2:
    int b = 2;
}

/// Даже с добавлением таких извращений

switch (x) {
  case 1:
    if (a == 1) {
  case 2:
    int b = 2;
  }
}

And this is no longer
int x = 1;
switch (x) {
  case 2:
    int b = 2;
  case 1:;
}

And it seems like everything is explained. on the one hand, b is visible everywhere after its declaration, but in case 1 we can come bypassing this declaration, as if a contradiction.
There are no such problems in C, because variables must be declared at the beginning of the block.
There are 2.5 ways to solve.
1. Wrap the actions in the case with curly braces
1.5 Move them into a separate function
2. Describe the variable before the switch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question