Question

I'm trying to make a macros that calculates 2 n and 2 n - 1. That would be:

#define b(n) (2 << (n))
#define a(n) ((b(n))-1)

However for some reason this cast it as int, but I'm willing to use unsigned long int. Does anyone know how to solve this? I have thought about using inline functions, however I don't fully grasp the difference between function-like macros and inline functions.

Was it helpful?

Solution

OP wants unsigned long int, then use that type in your macro

#define b(n) (1UL<<((unsigned)(n)))

When OP used (2 << (n)), the result is type int, as 2 is an int. Operator << with an int and unsigned results in int. Instead use unsigned throughout.


Further, to emulate power(2,n), certainly the OP wanted to use 1 shifted left, rather than 2 shifted left.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top