Is it possible to perform a switch with a hexadecimal case statement?
for example:
switch (integer) {
case: 1
function();
break;
case: F:
function();
break;
}
g++ complains saying:
example.cpp: In function ‘int main()’:
example.cpp:148:18: error: ‘F’ was not declared in this scope
I assume the compiler is trying to treat F
as a variable. I know instead of F
I could just use the value 15
but hex would be more convenient.
Solutions for other control statements would be nice too.
In C programming language, hexadecimal value is represented as 0x or 0X and to input hexadecimal value using scanf which has format specifiers like %x or %X.
There is no special type of data type to store Hexadecimal values in C programming, Hexadecimal number is an integer value and you can store it in the integral type of data types (char, short or int).
In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).
Octal and hexadecimal data types are integer types that are available in most computer languages. They provide a convenient notation for the construction of integer values in the binary number system. All integer values are expressed in computer memory by setting the values of binary digits.
In C, and presumably C++ as well, you can use any integer constant in a switch statement. That's not your problem.
Your problem is that F
isn't a constant, it's a variable name. To specify your constant in hex, use a leading 0x
, e.g. 0xf
.
The same thing applies in any other context that can take a (decimal) value - you get hex by using a leading 0x
. Or if you want octal for some reason, use a leading 0
, without the x.
Thus 017
, 0xf
and 15
are all the same number, and can be used interchangeably in c.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With