Considering that, in the general case, a modification of the elements of the vector may be present in do smth , and also that each subsequent if if there are no commands like break , return , continue ... in do smth will require checking, the equivalent code with the switch will be quite strange (and that’s all equal to contain if ):
for (size_t i = 0; i < vec.size(); i++) { int visited = 0; again: switch(vec[i]) { case 1: if (visited >= 1) break; visited = 1; /* do smth... */ goto again; case 2: if (visited >= 2) break; visited = 2; /* do smth... */ goto again; case 3: if (visited >= 3) break; visited = 3; /* do smth... */ goto again; case 4: if (visited >= 4) break; visited = 4; /* do smth... */ goto again; case 5: if (visited >= 5) break; visited = 5; /* do smth... */ goto again; } }
You can slip a macro here:
#define v(i) if (visited >= i) break; visited = i
But it would still look no less strange:
for (size_t i = 0; i < vec.size(); i++) { int visited = 0; again: switch(vec[i]) { case 1: v(i); /* do smth... */ goto again; case 2: v(i); /* do smth... */ goto again; case 3: v(i); /* do smth... */ goto again; case 4: v(i); /* do smth... */ goto again; case 5: v(i); /* do smth... */ goto again; } }
PS at the same time, I replaced int with size_t , since the size of the vector is still unsigned.