1

So here is my problem, I was writing just a simple code in C++, since I am a beginner, and I stumbled upon a problem. First at all the code:

    case 4:
        std::cout << "a b c: \n";
        std::cin >> a >> b >> c;
        auto[newA, newB, newC] = calculateSSS(A, B, C, a, b, c);
        std::cout << "A, B and C are: " << std::setprecision(1) << std::fixed << newA << "; " << newB << "; " << newC << '\n';
        break;

    default:
        exit;
}

return 0;

The terminal tells me that the variables in "auto" (so newA, newB and newC) crosses initialization and it doesn't tell me anything about default, so I don't know what the error might be.

Everywhere else, without the default, it worked out. Also, if I remove the default case, it works out just fine out of nowhere. Please anyone tell me what the problem seems to be

Deres
  • 11
  • 1
  • 1
    Welcome to StackOverflow. Please take a [tour] and see [ask]. Specifically you'll need to provide a [mre], including the exact error mesages you get. – wohlstad Apr 27 '23 at 06:31
  • You're not allowed to define and initialize variables inside cases. You cold easily solve this by putting all the code of your case (except the `break` of course) in a separate function that you call. – Some programmer dude Apr 27 '23 at 06:34
  • 1
    Wow. This site has gotten so snarky. It's no wonder we are all moving to ChatGPT: ask a robot trained on this site that doesn't have an attitude. The reason is down to the fact that the separate `case` statements don't introduce another scope. So the compiler pukes as the declaration `auto[newA, newB, newC]` is in some branches and not others. Clearly the problem goes away if there is only one `case`. You can introduce scope blocks `{` and `}` around the specific `case` as a solution. I dislike having functions that are only called in one place so prefer that. – Bathsheba Apr 27 '23 at 07:09

0 Answers0