As we know that we can not initialize a variable in any of the case
in switch
, unless it is the last case
of the respective switch
, as initialization of variables does require the definition to execute at runtime (since the value of the initializer must be determined at that point),
BUT
We also know that a constexpr
variable will get initialized or get replaced in the code with its value during the compilation process itself.
So I tried the below code i.e., initializing a constexpr
variable Z
in case 2
(which is the not the last case
of the switch
) but I am getting an error stating as:
crosses initialization of ‘constexpr const int z’ 24 |
constexpr int z{ 4 }; // illegal: initialization is not allowed if subsequent cases exist
May someone please clarify the reason behind this error?
Thanking you in Advance!
#include <iostream>
int main()
{
switch (1)
{
int y;
case 1:
y = 4;
break;
case 2:
constexpr int z{ 4 }; // ERROR
break;
case 3:
y=5;
break;
}
return 0;
}