What are Case Statement Data Types?
If-then statements are critical to any programming language. They allow programs to perform different actions in different circumstances. The most basic example of an if-then statement is when you log in to your email account. "If" your password is correct, "then" you can see your mail. "If" you give the wrong password, "then" you are told your password was incorrect. Case statements are derivations of if-then statements.
-
Switch Case Statements
-
Case statements are the functional components of what are called "switch case" statements in the C programming language, or simply "switch" statements in Java. These are like if-then statements, but somewhat streamlined. Instead of a number of separate "if-then" statements, switch-like statements take a single variable, then have a list of case statements. Each one specifies a possible value of the variable passed into the switch-like function, and if the variable matches a case statement's conditional, or a value to which the variable passed into the switch like function is being compared, then the corresponding code is executed by the computer.
Switch Case Statements vs. If-Then Statements
-
In basic function, switch case statements work like if-then statements: each gives a series of possibilities of code that could be executed. Switch case statements have the benefit of giving the programmer a cleaner syntax to examine than traditional if-then statements. Case statements consist solely of "case" followed by the conditional, then the code to execute beneath it. This allows the programmer to quickly ascertain all the relevant information about the block of code when he is debugging a program.
-
Data Types
-
Case statements can handle most data types. These include byte, which can hold binary data, char, which holds a single character, and int, which holds an integer. They cannot handle more advanced data types, such as float or decimal, which hold numbers with decimal components. They they can handle enumerated data types, though. These are data types in which the user declares a name for a custom variable, then defines the possible values the variable can hold.
Data Type Consistency
-
Regardless of the data type the programmer is using in the case statement, it has to be consistent between the variable that the computer will compare to case statements and the case statement conditionals. A computer can only compare int variables to int variables, char variables to char variables, enumerated variables to another instance of that same enumerated variable and so on. If there is a discrepancy between the two data types, then the program will fail to compile.
-
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images