Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 823 Vote(s) - 3.56 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Hexadecimal Value In C++ Switch Statement

#1
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.
Reply

#2
Yes; prefix the hex values with `0x` to have the compiler treat them as hex literals.
Similarly, prefix with `0` to have them be treated as octal.
Reply

#3
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.
Reply

#4
If you want to assign a hex value to a variable you have to use a prefix `0x`, in your case `int var = 0xF`
Reply

#5
123 is treated as decimal.<br>
0123 is treated as octal.<br>
0x123 is treated as hexadecimal.<br>
0b101 is treated as binary (C++14).<br>

You need to use 0xF.
Reply

#6
yes, it is. use this syntax:

unsigned char buffer[12];
switch (buffer[0]) {
case 0x01:
// your code
break;
case 0xAA:
// your code
break;
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through