2

I need several integer constants with 2^n and 2^n - 1 in my GNU c++ code.

What is a good practise to keep the code readable? The code uses decimal values at the moment 4294967296 and 65536 which is hard to debug in future.

2^12 is not implemented in standard C++ and pow(2.0,12.0) uses double.

if (buffer_length == 4294967295){ } // code example, I want to make more readable
Jonas Stein
  • 6,826
  • 7
  • 40
  • 72

2 Answers2

3

You can use the shift left operator:

if (buffer_length == 1 << 12){ } 
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
0

Use hex. It should be pretty easy for anyone to figure out that it's a special number.

James
  • 9,064
  • 3
  • 31
  • 49
  • @JonasStein You're mixing up hex and binary. – James Jun 13 '15 at 18:36
  • hex is not so easy to read with human eyes: `2^64 = 0x10000000000000000` and `2^64-1 = 0xffffffffffffffff` One has to count the number of f and 0 which is error prone and difficult to read. – Jonas Stein Jun 13 '15 at 18:37
  • 3
    @JonasStein then do what everyone else does and give the constants names and use those instead of having magic numbers all over. – James Jun 13 '15 at 18:40