switch-statement interview questions
Top switch-statement frequently asked interview questions
I tried searching around but couldn't find anything that would help me out.
I'm trying to do this in SQL:
declare @locationType varchar(50);
declare @locationID int;
SELECT column1, column2
FROM viewWhatever
WHERE
CASE @locationType
WHEN 'location' THEN account_location = @locationID
WHEN 'area' THEN xxx_location_area = @locationID
WHEN 'division' THEN xxx_location_division = @locationID
I know that I shouldn't have to put '= @locationID' at the end of each one but I can't get the syntax even close to being correct. SQL keeps complaining about my '=' on the first WHEN line...
Help!
Source: (StackOverflow)
I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:
switch (val)
{
case VAL:
// This won't work
int newVal = 42;
break;
case ANOTHER_VAL:
...
break;
}
The above gives me the following error (MSC):
initialization of 'newVal' is skipped by 'case' label
This seems to be a limitation in other languages too. Why is this such a problem?
Source: (StackOverflow)
The best way I can describe what I'm looking for is to show you the failed code I've tried thus far:
case car
when ['honda', 'acura'].include?(car)
# code
when 'toyota' || 'lexus'
# code
end
I've got about 4 or 5 different when
situations that should be triggered by approximately 50 different possible values of car
. Is there a way to do this with case
blocks or should I try a massive if
block?
Source: (StackOverflow)
I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a switch
or case
statement, but Python does not appear to have a switch
statement. What are the recommended Python solutions in this scenario?
Source: (StackOverflow)
Why can't I switch on a String
?
Is this functionality going to be put into a later Java version?
Can someone explain why I can't do this, as in, the technical way Java's switch
statement works?
Source: (StackOverflow)
Is a switch
statement actually faster than an if
statement?
I ran the code below on Visual Studio 2010's x64 C++ compiler with the /Ox
flag:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_COUNT (1 << 29)
size_t counter = 0;
size_t testSwitch()
{
clock_t start = clock();
size_t i;
for (i = 0; i < MAX_COUNT; i++)
{
switch (counter % 4 + 1)
{
case 1: counter += 4; break;
case 2: counter += 3; break;
case 3: counter += 2; break;
case 4: counter += 1; break;
}
}
return 1000 * (clock() - start) / CLOCKS_PER_SEC;
}
size_t testIf()
{
clock_t start = clock();
size_t i;
for (i = 0; i < MAX_COUNT; i++)
{
const size_t c = counter % 4 + 1;
if (c == 1) { counter += 4; }
else if (c == 2) { counter += 3; }
else if (c == 3) { counter += 2; }
else if (c == 4) { counter += 1; }
}
return 1000 * (clock() - start) / CLOCKS_PER_SEC;
}
int main()
{
printf("Starting...\n");
printf("Switch statement: %u ms\n", testSwitch());
printf("If statement: %u ms\n", testIf());
}
and got these results:
Switch statement: 5261 ms
If statement: 5196 ms
From what I've learned, switch
statements apparently use jump tables to optimize the branching.
Questions:
What would a basic jump table look like, in x86 or x64?
Is this code using a jump table?
Why is there no performance difference in this example? Is there any situation in which there is a significant performance difference?
Disassembly of the code:
testIf:
13FE81B10 sub rsp,48h
13FE81B14 call qword ptr [__imp_clock (13FE81128h)]
13FE81B1A mov dword ptr [start],eax
13FE81B1E mov qword ptr [i],0
13FE81B27 jmp testIf+26h (13FE81B36h)
13FE81B29 mov rax,qword ptr [i]
13FE81B2E inc rax
13FE81B31 mov qword ptr [i],rax
13FE81B36 cmp qword ptr [i],20000000h
13FE81B3F jae testIf+0C3h (13FE81BD3h)
13FE81B45 xor edx,edx
13FE81B47 mov rax,qword ptr [counter (13FE835D0h)]
13FE81B4E mov ecx,4
13FE81B53 div rax,rcx
13FE81B56 mov rax,rdx
13FE81B59 inc rax
13FE81B5C mov qword ptr [c],rax
13FE81B61 cmp qword ptr [c],1
13FE81B67 jne testIf+6Dh (13FE81B7Dh)
13FE81B69 mov rax,qword ptr [counter (13FE835D0h)]
13FE81B70 add rax,4
13FE81B74 mov qword ptr [counter (13FE835D0h)],rax
13FE81B7B jmp testIf+0BEh (13FE81BCEh)
13FE81B7D cmp qword ptr [c],2
13FE81B83 jne testIf+89h (13FE81B99h)
13FE81B85 mov rax,qword ptr [counter (13FE835D0h)]
13FE81B8C add rax,3
13FE81B90 mov qword ptr [counter (13FE835D0h)],rax
13FE81B97 jmp testIf+0BEh (13FE81BCEh)
13FE81B99 cmp qword ptr [c],3
13FE81B9F jne testIf+0A5h (13FE81BB5h)
13FE81BA1 mov rax,qword ptr [counter (13FE835D0h)]
13FE81BA8 add rax,2
13FE81BAC mov qword ptr [counter (13FE835D0h)],rax
13FE81BB3 jmp testIf+0BEh (13FE81BCEh)
13FE81BB5 cmp qword ptr [c],4
13FE81BBB jne testIf+0BEh (13FE81BCEh)
13FE81BBD mov rax,qword ptr [counter (13FE835D0h)]
13FE81BC4 inc rax
13FE81BC7 mov qword ptr [counter (13FE835D0h)],rax
13FE81BCE jmp testIf+19h (13FE81B29h)
13FE81BD3 call qword ptr [__imp_clock (13FE81128h)]
13FE81BD9 sub eax,dword ptr [start]
13FE81BDD imul eax,eax,3E8h
13FE81BE3 cdq
13FE81BE4 mov ecx,3E8h
13FE81BE9 idiv eax,ecx
13FE81BEB cdqe
13FE81BED add rsp,48h
13FE81BF1 ret
testSwitch:
13FE81C00 sub rsp,48h
13FE81C04 call qword ptr [__imp_clock (13FE81128h)]
13FE81C0A mov dword ptr [start],eax
13FE81C0E mov qword ptr [i],0
13FE81C17 jmp testSwitch+26h (13FE81C26h)
13FE81C19 mov rax,qword ptr [i]
13FE81C1E inc rax
13FE81C21 mov qword ptr [i],rax
13FE81C26 cmp qword ptr [i],20000000h
13FE81C2F jae testSwitch+0C5h (13FE81CC5h)
13FE81C35 xor edx,edx
13FE81C37 mov rax,qword ptr [counter (13FE835D0h)]
13FE81C3E mov ecx,4
13FE81C43 div rax,rcx
13FE81C46 mov rax,rdx
13FE81C49 inc rax
13FE81C4C mov qword ptr [rsp+30h],rax
13FE81C51 cmp qword ptr [rsp+30h],1
13FE81C57 je testSwitch+73h (13FE81C73h)
13FE81C59 cmp qword ptr [rsp+30h],2
13FE81C5F je testSwitch+87h (13FE81C87h)
13FE81C61 cmp qword ptr [rsp+30h],3
13FE81C67 je testSwitch+9Bh (13FE81C9Bh)
13FE81C69 cmp qword ptr [rsp+30h],4
13FE81C6F je testSwitch+0AFh (13FE81CAFh)
13FE81C71 jmp testSwitch+0C0h (13FE81CC0h)
13FE81C73 mov rax,qword ptr [counter (13FE835D0h)]
13FE81C7A add rax,4
13FE81C7E mov qword ptr [counter (13FE835D0h)],rax
13FE81C85 jmp testSwitch+0C0h (13FE81CC0h)
13FE81C87 mov rax,qword ptr [counter (13FE835D0h)]
13FE81C8E add rax,3
13FE81C92 mov qword ptr [counter (13FE835D0h)],rax
13FE81C99 jmp testSwitch+0C0h (13FE81CC0h)
13FE81C9B mov rax,qword ptr [counter (13FE835D0h)]
13FE81CA2 add rax,2
13FE81CA6 mov qword ptr [counter (13FE835D0h)],rax
13FE81CAD jmp testSwitch+0C0h (13FE81CC0h)
13FE81CAF mov rax,qword ptr [counter (13FE835D0h)]
13FE81CB6 inc rax
13FE81CB9 mov qword ptr [counter (13FE835D0h)],rax
13FE81CC0 jmp testSwitch+19h (13FE81C19h)
13FE81CC5 call qword ptr [__imp_clock (13FE81128h)]
13FE81CCB sub eax,dword ptr [start]
13FE81CCF imul eax,eax,3E8h
13FE81CD5 cdq
13FE81CD6 mov ecx,3E8h
13FE81CDB idiv eax,ecx
13FE81CDD cdqe
13FE81CDF add rsp,48h
13FE81CE3 ret
Update:
Interesting results here and here. Not sure why one is faster and one is slower, though.
Source: (StackOverflow)
Possible Duplicate:
When converting a project to use ARC what does “switch case is in protected scope” mean?
Got the following xcode:
But when i try to put something in case 1 (or empty) it's giving me an error?
Weird problem because i dont know what a protected switch is and how i should fix it. Does anyone has a solution or clue to fix this? Weird..
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIViewController *controller;
switch(indexPath.row) {
case 0:
NSLog(@"0");
//create instance of EKEventStore
EKEventStore *eventStore = [[EKEventStore alloc] init];
//creating instance of EKEvent
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
//setting the appropriate properties of the new event
event.title = @"Woow";
//event.startDate = [[NSDate alloc] init];
NSDateComponents *myDate2 = [[NSDateComponents alloc] init];
[myDate2 setDay:13];
[myDate2 setMonth:12];
[myDate2 setYear:2011];
[myDate2 setHour:00];
[myDate2 setMinute:34];
event.startDate = [[NSCalendar currentCalendar] dateFromComponents:myDate2];
event.endDate = [[NSDate alloc] initWithTimeInterval:3600 sinceDate:event.startDate];
event.location = @"game2";
event.notes = @" game";
event.alarms = [NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:event.startDate]];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *error;
[eventStore saveEvent:event span:EKSpanThisEvent error:&error];
break;
case 1:
NSLog(@"1");
break;
}
{
self.EKController.title = [self.EKList objectAtIndex:[indexPath row]];
}
}
@end
But an error:

Source: (StackOverflow)
I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at a max of 100 and with my limited programming ability at this point I am doing something like this.
public void getHealed(){
if(health <= 85)
health += 15;
else if(health == 86)
health += 14;
else if(health == 87)
health += 13;
}// this would continue so that I would never go over 100
I understand my syntax about isnt perfect but my question is, what may be a better way to do it, because I also have to do a similar thing with the damage points and not go below 0.
Source: (StackOverflow)
This question already has an answer here:
I saw a few answers to this issue, and I get it — you can't declare and assign variables inside a switch
. But I'm wondering if the following is correct at throwing an error saying
error: expected expression before 'int'
Code:
switch (i) {
case 0:
int j = 1;
break;
}
Why would putting a call to NSLog()
before it result in no errors?
switch (i) {
case 0:
NSLog(@"wtf");
int j = 1;
break;
}
Source: (StackOverflow)
Possible Duplicate:
C# - Is there a better alternative than this to ‘switch on type’?
If you want to switch
on a type of object, what is the best way to do this?
Code snippet
private int GetNodeType(NodeDTO node)
{
switch (node.GetType())
{
case typeof(CasusNodeDTO):
return 1;
case typeof(BucketNodeDTO):
return 3;
case typeof(BranchNodeDTO):
return 0;
case typeof(LeafNodeDTO):
return 2;
default:
return -1;
}
}
I know this doesn't work that way, but I was wondering how you could solve this.
Is an if/else
statement appropriate in this case?
Or do you use the switch and add .ToString()
to the type?
Source: (StackOverflow)
How do I write a swtich for the following conditional?
If the url contains "foo", then settings.base_url is "bar".
The following is achieving the effect required but I've a feeling this would be more manageable in a switch:
var doc_location = document.location.href;
var url_strip = new RegExp("http:\/\/.*\/");
var base_url = url_strip.exec(doc_location)
var base_url_string = base_url[0];
//BASE URL CASES
// LOCAL
if (base_url_string.indexOf('xxx.local') > -1) {
settings = {
"base_url" : "http://xxx.local/"
};
}
// DEV
if (base_url_string.indexOf('xxx.dev.yyy.com') > -1) {
settings = {
"base_url" : "http://xxx.dev.yyy.com/xxx/"
};
}
Source: (StackOverflow)
Is there any way of using an 'OR' operator or equivalent in a php switch? For example, something like this:
switch ($value) {
case 1 || 2:
echo 'the value is either 1 or 2';
break;
}
Source: (StackOverflow)
Consider the following switch
statement:
switch( value )
{
case 1:
return 1;
default:
value++;
// fall-through
case 2:
return value * 2;
}
This code compiles, but is it valid (= defined behavior) for C90/C99? I have never seen code where the default case is not the last case.
EDIT:
As Jon Cage and KillianDS write: this is really ugly and confusing code and I am well aware of it. I am just interested in the general syntax (is it defined?) and the expected output.
Source: (StackOverflow)