skip to Main Content

I am trying to figure out differences between if statements and switch statements. I have written this code:

`int number = 3;
switch (number)
{
    case 1:
       Console.WriteLine("1");
       break;
    case 3:
       Console.WriteLine("FOUND");
       break;
    default:
       Console.WriteLine("def");
       break;
}`

I am trying to work it out by using debugger line by line(F11(visual studio)). What I do not understand is if this were an if statement such as below:
int number = 3; if (number == 1) { Console.WriteLine("1"); } else if (number == 3) { Console.WriteLine("333333"); } else { Console.WriteLine("def"); }

it would execute line by line and it would check each if block and if it is false it would jump to the next conditional statement. However with switch case I can not understand where/when or how does it check which switch case is relevant at the beginning of switch statement. Do case 1,3 and the default are check at the same time? How is this possible is everything to be executed line by line?

Despite trying to diffent approaches with if statements and switch statements, still can not understand how switch cases are selected.

2

Answers


  1. Even before running the javascript, the js skims through the code and a global execution control block is created and this is where it assigns the memory & code. In your case it assigns the memory to variable and function i.e switch case here is assigned the value even before running the actual code & this is the reason why switch cases get executed at the beginning.

    Login or Signup to reply.
  2. if statement:
    When the C# code containing an if statement is compiled, it’s translated into machine code instructions that represent a conditional branch. The processor evaluates the condition, and based on the result, it either jumps to the memory address where the code block associated with the true condition is located or proceeds to the next instruction following the if block.

    switch statement:
    The switch statement works differently under the hood. It’s generally compiled into a table of jump addresses or a series of comparison and branching instructions based on the cases.

    if statements involve direct comparison and conditional branching based on the evaluated condition. On the other hand, switch statements are often compiled into more optimized structures like jump tables or a sequence of comparisons to efficiently handle multiple cases.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search