The switch statement is a powerful construct in C that allows you to clearly express complex if/else if/else blocks as a single statement. By providing this construct, you can write code that’s easier to understand and maintain. The downside to this is that you must use constant values for the case statements, and these constants must sensibly compare using the == operator. So, for instance, it is possible to have integers in your case statements, but not possible to have strings. Attempting to compare strings with == will not work reliably due to pointer comparisons. However, there is a solution that has the power and clarity of a switch statement in C++, and thanks to lambda functions in C++11, it can be elegant as well.
Continue reading
Who
Aaron Ballman is a Principal Compiler Engineer for Intel and is the lead maintainer of the Clang open source compiler. He has two decades of experience writing cross-platform frameworks in C/C++, compiler & language design, and software engineering best practices and is currently a voting member of the C (WG14) and C++ (WG21) standards committees.
In case you can't figure it out easily enough, the views expressed here are my personal views and not the views of my employer, my past employers, my future employers, or some random person on the street. Please yell only at me if you disagree with what you read.
Search