+ 3

How to identify a integer number is +ve or - ve without if-else

26th Jun 2016, 8:25 AM
Ramesh Marisa
11 Réponses
+ 5
cout << (unsigned(a) <= unsigned(-1)/2 ? "+" : "-") << endl; For any int a. If you dont want to use any conditional: bool isPositive = unsigned(a) <= unsigned(-1)/2;
26th Jun 2016, 2:20 PM
Garme Kain
Garme Kain - avatar
+ 3
you can do it with switch case also
27th Jun 2016, 6:15 AM
DEATH WALKER
DEATH WALKER - avatar
+ 1
the first bit of any variable of basic signed datatype represents the sign
26th Jun 2016, 8:43 AM
Mukul Kumar
Mukul Kumar - avatar
+ 1
Not first bit, last bit MSB represents sign and then how to write program
26th Jun 2016, 9:48 AM
Ramesh Marisa
+ 1
is it the left-most bit you are referring to in a binart number?
26th Jun 2016, 2:02 PM
Mukul Kumar
Mukul Kumar - avatar
+ 1
i want without / % operators
26th Jun 2016, 3:48 PM
Ramesh Marisa
+ 1
conditional expression ? : equivalent to if-else
26th Jun 2016, 3:49 PM
Ramesh Marisa
+ 1
#include <limits.h> int main() { int a = -9; bool isPositive = unsigned(a) <= INT_MAX; return 0; }
26th Jun 2016, 4:28 PM
Garme Kain
Garme Kain - avatar
+ 1
using relation operator in a statement is similar to if-else <= will generate if-else condition
26th Jun 2016, 4:31 PM
Ramesh Marisa
+ 1
int a = -1; bool isPositive = ~a & (1 << 8*sizeof(a) - 1); I hard coded the number 0x1f (31) and i dont like that because ints can be other size than 32 bits but I think this will do it. Edit: Corrected.
26th Jun 2016, 5:08 PM
Garme Kain
Garme Kain - avatar
0
use sizeof operator to identify int size
26th Jun 2016, 5:18 PM
Ramesh Marisa