user1772218
user1772218

Reputation: 125

C++ switch statement , how does this work

#include <iostream>
#include <sstream>

int main(int argc, char* argv[]) {
if ( argc != 2 ) {
 std::cout << "usage: " << argv[0] << " <n> " << std::endl;
 return 0;
}
std::stringstream strm;
strm << argv[1];
int count = 0;
int number;
strm >> number;
switch ( number ) {
 case 0: ++count; 
 case 1: ++count; 
 case 2: ++count; 
 case 3: ++count; 
 case 4: ++count; 
 }

    std::cout << "count: " << count << std::endl;
    return 0;
 }

I know this is a novice question, but i just started with C++. I took a game design course and this is the first example prof has on the SVN. When I run the prog after compiling,

./run 4 (i.e. I give argument 4) I get an output: count: 1

./run 3 I get an output: count: 2

./run 1 count: 4

./run 0 count: 5

Since count is initialized to 0, how come ./run 1 gives 4 or ./run 0 give count 5.

I am really sorry for such a silly question, but I would appreciate any explanation.

Thanks in Advance Regards

Upvotes: 2

Views: 4115

Answers (2)

David D
David D

Reputation: 1591

A switch statement defines where to enter a set of code.

switch ( number ) {
 case 0: ++count; //entrance point with number= 0
 case 1: ++count; //entrance point with number= 1
 case 2: ++count; //entrance point with number= 2
 case 3: ++count; //entrance point with number= 3
 case 4: ++count; //entrance point with number= 4
}

Inherently there is no exit except for getting to the end of the switch. However, it is possible to add a "break;" statement anywhere under a case to cause the code to exit the switch early (or break out of scope).

Additionally, but slightly off topic, the keyword "default" should be used in a case statement. The default keyword is called when the number doesn't have a defined case. Example, using the case above, is if someone sent the number 6 to the case.

Upvotes: 3

Chad
Chad

Reputation: 19052

With a switch statement, when control is passed to a case label, the code will continue on through all other case labels until a break or return (or other flow control mechanism) is encountered. This can be useful for unifying logic of specific cases, and can also be used for more complicated tasks. See for example: a Duff's Device.

Upvotes: 10

Related Questions