Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal Value In C++ Switch Statement

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.

like image 738
Brandon Kreisel Avatar asked Apr 27 '13 21:04

Brandon Kreisel


People also ask

What is the hexadecimal value of C?

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.

What data type is Hex in C?

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).

What is 0x in C?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).

What data type is hexadecimal?

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.


1 Answers

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.

like image 70
Arlie Stephens Avatar answered Oct 02 '22 07:10

Arlie Stephens