Saturday 15 February 2014

compiler construction - Are switch-case constructs implemented as binary search? -



compiler construction - Are switch-case constructs implemented as binary search? -

i'm wondering how switch-case statement implemented:

example

say 1 has next code:

scanner sc = new scanner(system.in); int v = sc.nextint(); switch(v) { case 0 : system.out.println("zero"); break; case 1 : system.out.println("one"); break; case 2 : system.out.println("two"); break; //... default : system.out.println("no 1 digit number"); }

one can implement as:

if(v == 0) { system.out.println("zero"); } else if(v == 1) { system.out.println("one"); } else if(v == 2) { system.out.println("two"); } //... else { system.out.println("no 1 digit number"); }

but more efficient programme is:

if(v >= 0 && v <= 9) { if(v <= 5) { if(v <= 2) { if(v <= 1) { if(v == 0) { system.out.println("zero"); } else { system.out.println("one"); } else { system.out.println("two"); } } //... } //... } else { system.out.println("no 1 digit number"); }

this can of import since there programs (like compiler compilers) write java/c#/c++ source code , generate big switch statements.

the way switch statements implemented depends on 'case' list. when set of 'case' dense, jump table can used (like goto label[v] statement, if existed). much faster binary search.

compiler-construction switch-statement

No comments:

Post a Comment