+ 22

I need a little bit of help on statements.

I am developing a small code that takes user input. After that, the second input variable is then checked. Let us say that there are more than two choices. If, for example, there are three choices. I know that the first choice should be an if statement and the last one should be else. But, my question is: what is in between? int a ; int b ; cin >> a ; // user inputs: 20 cin >> b ; // user inputs: 2 if ( b == 1 ) { // code } ???? ( b == 2 ) { // code } else ( b == 3 ) { // code }

26th Dec 2017, 6:38 AM
Edwin Pratt
Edwin Pratt - avatar
8 odpowiedzi
+ 8
@Edwin Pratt In short, Switch faster than else if. If you're planning to use small amount of else if then the performance will be relatively equals, but if we're talking about much more, then switch would be faster. http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx
26th Dec 2017, 8:22 AM
Cain Eviatar
Cain Eviatar - avatar
+ 22
else if. You can write else if statements as many as you need. if ( b == 1 ) { // code } else if( b == 2 ) { // code } else if ( b == 3 ) { // code } else{ // code }
26th Dec 2017, 6:45 AM
Shamima Yasmin
Shamima Yasmin - avatar
+ 19
Thank you @Shamima Yasmin
26th Dec 2017, 6:55 AM
Edwin Pratt
Edwin Pratt - avatar
+ 17
@Cain Eviavar Thank you! May you please explain why you recommend me using switch statements?
26th Dec 2017, 8:16 AM
Edwin Pratt
Edwin Pratt - avatar
+ 16
@Cain Eviatar AMAZING!!!
26th Dec 2017, 8:29 AM
Edwin Pratt
Edwin Pratt - avatar
+ 4
in addition, I would suggest using Switch instead of a lot of else if...
26th Dec 2017, 7:32 AM
Cain Eviatar
Cain Eviatar - avatar
+ 3
u can use switch instead of if else
27th Dec 2017, 7:46 AM
Abdulshaqoor Tom
Abdulshaqoor Tom - avatar
+ 1
if/else is easier but for your scenario switch is better
4th Jan 2018, 12:47 AM
Toluwase Shoniran