0
for(int i=0; i<3; i++){
 switch(i)
    case 0:
    LAYOUT[i].x=i;
    LAYOUT[i].y=i;
    case 1:
    LAYOUT[i].x=funcx(i);
    LAYOUT[i].y=funcy(i);
    case 2:
    LAYOUT[i].x=2*i;
    LAYOUT[i].y=4*i;}

This is the simplified code I am having problem with. What I want this code to do is, when i=0, do whats in case 0, when i=1, do whats in case 1 and so on.

But here is the problem.. for example when i=1, it calculates the correct .x (case 1) value but for .y it calculates for a different i such as 0 or 2. I tried to put {} around all the code inside each case, but it made no difference. I also tried i from 1 to 3 instead..

ofstream Zone1H;
        Zone1H.open("TEST.txt");
for(int l=0; l<5; l++)          
            Zone1H<<LAYOUT[i].x<<"  "<<LAYOUT[i].y<<endl;

Could my saving part be the issue? I never had problem with this part though..

3
  • 6
    You forgot to put break between the cases, so it's falling through to the next case.
    – Barmar
    Commented Aug 25, 2015 at 0:53
  • 1
    Also, the switch statement needs to have opening and closing braces. switch(i) { ... }Those are not optional.
    – jpw
    Commented Aug 25, 2015 at 1:02
  • You might find this SO question/answer of interest: stackoverflow.com/questions/252489/… Commented Aug 25, 2015 at 1:02

3 Answers 3

5

You're missing a break at the end of each case. It's falling through all the cases and only the last one is taking effect.

for(int i=0; i<3; i++){
  switch(i){
    case 0:
      LAYOUT[i].x=i;
      LAYOUT[i].y=i;
      break; // <-- add this
    case 1:
      LAYOUT[i].x=funcx(i);
      LAYOUT[i].y=funcy(i);
      break; // <-- add this
    case 2:
      LAYOUT[i].x=2*i;
      LAYOUT[i].y=4*i;
      break; // <-- add this
  }
}
1

The break at the end of each case, takes you out of the switch statement and back to the top of the for loop so you won't traverse the other cases within the switch condition.

for(int i=0; i<3; i++){
 switch(i){
  case 0:
    LAYOUT[i].x=i;
    LAYOUT[i].y=i;
  break;
  case 1:
    LAYOUT[i].x=funcx(i);
    LAYOUT[i].y=funcy(i);
  break;
  case 2:
    LAYOUT[i].x=2*i;
    LAYOUT[i].y=4*i;
  break;
 }
}
1
  • Just like questions shouldn't be simple code dumps neither should answers. At least make an attempt to explain the problem and describe how to fix it and why. Commented Aug 25, 2015 at 1:12
0

You need to look into the break statement. Which is very important when it comes to switch statements. Without the break it evaluates one of them as true and keeps looking at the remaining cases. If you adda break to each statement when it finds the correct case it will "break" out oof the switch and go on to the next number in the loop

Not the answer you're looking for? Browse other questions tagged or ask your own question.