Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ power of two macro

I am not as good with my powers of two as I should be so I thought maybe I could #define something.

Unfortunately I am very inexperienced when it comes to preprocessor directives and I couldn't figure out how to do things like for loops. I looked at:

  • http://www.cplusplus.com/doc/tutorial/preprocessor
  • https://msdn.microsoft.com/en-us/library/teas0593.aspx

But neither of them have examples of for loops. All I want is to be able to write something like pwrtwo(5) instead of using a calculator to figure out that 25 is 32.

like image 397
Ace shinigami Avatar asked Oct 19 '25 04:10

Ace shinigami


1 Answers

Why not do it right and use a function? This even allows us to generate the result at compile time using the powerfull constexpr!

template <class T>
constexpr T pwrtwo(T exponent) {
    return (T(1) << exponent);
}
like image 95
Jan Hohenheim Avatar answered Oct 20 '25 17:10

Jan Hohenheim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!