Hi Farticus,
I did run this code and it works as expected for aaa=1 and aaa=2 on WokWiki (did not have an Arduino handy).
(references: Arduino Documentation, chapter of my mini-course)
So I'm not sure what is happening on your setup 😞Â
Â
Code that I tested (cleaned it up a little):
int aaa = 0;
int z1 = 0;
int z2 = 0;
void setup() {
Serial.begin(9600);
Serial.println(" Begin");
}
void CasE() {
switch (aaa) {
case 1:
Serial.print(" START CASE 1");
z1 = 12 * 12 / 2 + 45 - 31;
Serial.print(" Z1 =");
Serial.println(z1);
break;
case 2:
Serial.print(" START CASE 2");
z2 = 12 * 12 / 2 + 45 - 31;
Serial.print(" Z2 =");
Serial.println(z2);
break;
}
}
void loop() {
aaa = 1;
CasE();
}
Â
A tip, of no critical importance for you code: Use code "blocks" when in doubt.
In C (and most other languages) you can create code blocks, where a group of code could be seen as one. In C like languages (C, C++, Obj. C, Java, javaScript, etc) this is typically done with enclosing accolades. The advantage can be that potentially breaking characters or code is now enclosed as a "block". This also improves code readability - but that is just my personal opinion 😉Â
For example:
void CasE() {
switch (aaa) {
case 1:
{
Serial.print(" START CASE 1");
z1 = 12 * 12 / 2 + 45 - 31;
Serial.print(" Z1 =");
Serial.println(z1);
break;
}
case 2:
{
Serial.print(" START CASE 2");
int z2 = 12 * 12 / 2 + 45 - 31;
Serial.print(" Z2 =");
Serial.println(z2);
break;
}
}
}
Â
Â
Another tip: avoid the use of global variables.
Global variables make your code inflexible, not reusable in other projects, and ... can cause unexpected behavior (bugs).
For example:
In your example code the globally defined "z2" is NOT the same variable as the "z2" used in the "Case()" function.Â
You've declared z1 and z2 as two global integers at the beginning of your code.
However ... in de CasE function you work "z1" without declaring it (so it uses the global variable).
"z2" on the other hand, you redefine in the "CasE()" function by saying "int z2 = ..." in the "case 2:" section.
So you declare "z2" now as a new and local variable and the global defined "z2" can no longer be accessed in the "CasE()" function.