Reputation: 193
I was solving the a question at HackerRank -
Question Link - https://www.hackerrank.com/challenges/maximum-element/problem
In one solution I used 'break' statement in switch-case, in another solution I didn't.
Solution was wrong when I didn't use break statement. What is the reason behind this ?
Input -
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
With break Statement -
#include <bits/stdc++.h>
using namespace std;
int main() {
int noOfTestCases;
cin>>noOfTestCases;
vector <int> st;
for(int x=0; x<noOfTestCases; x++){
int query;
cin>>query;
switch (query) {
case 1:
int number;
cin>>number;
if(st.empty()){
st.push_back(number);
}
else if(number > st[st.size()-1]){
st.push_back(number);
}
else{
st.push_back(st[st.size()-1]);
}
break;
case 2:
if(!st.empty()){
st.pop_back();
}
break;
case 3:
cout<<st[st.size()-1]<<endl;
}
}
}
//Output -
//26
//91
Without break statement -
#include <bits/stdc++.h>
using namespace std;
int main() {
int noOfTestCases;
cin>>noOfTestCases;
vector <int> st;
for(int x=0; x<noOfTestCases; x++){
int query;
cin>>query;
switch (query) {
case 1:
int number;
cin>>number;
if(st.empty()){
st.push_back(number);
}
else if(number > st[st.size()-1]){
st.push_back(number);
}
else{
st.push_back(st[st.size()-1]);
}
case 2:
if(!st.empty()){
st.pop_back();
}
case 3:
cout<<st[st.size()-1]<<" "<<query<<endl;
}
}
}
//Output -
//0
//0
//0
//0
//0
//0
//0
//0
//0
//0
Upvotes: 1
Views: 87
Reputation: 193
So I had a misconception about switch case statement -
What I thought - I thought that in switch case if the expression is equal to any case D, then further cases - E, F, G, will not be executed, irrespective of the break statement.
Reality - If an expression is equal to any case D, then further cases - E, F, G will also be executed if we don't use break statement.
Thanks Jeffrey and Paul Sanders to clarify this problem.
Upvotes: 2
Reputation: 1095
Consider the following code
switch (x) {
case 1:
std::cout << "one\n";
case 2:
std::cout << "two\n";
break;
case 3:
std::cout << "three\n";
}
If x
is 1 it will print both one
and two
. It will then exit the switch block due to the break
statement. Note that x
will not be compared with 2
after printing "one", it will directly fall-through to printing "two".
Upvotes: 4