[SOLVED] Compiler problem: switch statement

Status
Not open for further replies.

ayeshasalman

Newbie
Joined
Feb 6, 2020
Messages
1
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Activity points
19
Compiler problem: switch statement
Hi Guys This is Ayesha It has been long time that I'm working on a project of arduino and I have searched my question here and there but couldn’t find it. Well let me explain the issue I'm getting with my arduino switch and its timing.

I believe the arduino that I got from an online electronic store as i think it's SWITCH statement has some compile time problems.

If I try to declare a boolean variable in a CASE statement as illustrated in "case 2: in the snippet below, the compiler throws an error.

I add this to the other CASE statement problem I flagged earlier: ie. the compiler does not throw an error if you misspell "default" as "defalut.")

Code:
switch (var) {
case 1:
//do something when var equals 1
break;
case 2:
boolean X;
//do something when var equals 2
break;
default:
// if nothing else matches, do the default
// default is optional
break;
}

This appears to be a problem with the compiler, NOT my code, and it seems to happen only with nested SWITCH statements.

Thank in advance for your prompt response.
 

What makes you think that a variable declaration is allowed at this point? According to C language specification, a switch label is just a label. A variable declaration is however only permitted at the top of compound statement. So you would at least need braces after the label to start a new block.
Generally, what's the purpose of the declaration in the middle of a switch construct?
 

This behavior is fairly compiler-dependent, I think - and this "declare variables where you use them" in C-files seems to be the splatter effect from C++/Python programmers writing C code, and they carry those habits with them regarding namespace-usage variables. If you use curly braces to create a code block in the case 2: section and put the variable within those braces, it *may* allow it - I know various Gnu-based C / C++ Microchip compilers will.
Some compilers may have issues with large, complex, nested Switch statements just as a matter of limitations or bugginess. What brand/revision of Arduino toolset are you using?
 
Reactions: FvM

    FvM

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…