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..

user2864740
  • 60,010
  • 15
  • 145
  • 220
hoffnung
  • 7
  • 4
  • 6
    You forgot to put `break` between the cases, so it's falling through to the next case. – Barmar Aug 25 '15 at 00:53
  • 1
    Also, the switch statement needs to have opening and closing braces. `switch(i) { ... }`Those are not optional. – jpw Aug 25 '15 at 01:02
  • You might find this SO question/answer of interest: http://stackoverflow.com/questions/252489/why-was-the-switch-statement-designed-to-need-a-break – Michael Burr Aug 25 '15 at 01:02

3 Answers3

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
  }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
gavinb
  • 19,278
  • 3
  • 45
  • 60
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;
 }
}
Sterls
  • 723
  • 12
  • 22
  • 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. – Captain Obvlious Aug 25 '15 at 01: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

JackV
  • 218
  • 2
  • 12