I found this array declaration in open source software. It reads data from csv files, compares the tuples, and outputs the best tuples.
static const uint32_t SHIFTS[] = { 1 << 0, 1 << 1, 1 << 2, 1 << 3, 1 << 4,
1 << 5, 1 << 6, 1 << 7, 1 << 8, 1 << 9, 1 << 10, 1 << 11, 1 << 12, 1 << 13,
1 << 14, 1 << 15, 1 << 16, 1 << 17, 1 << 18, 1 << 19, 1 << 20, 1 << 21,
1 << 22, 1 << 23, 1 << 24, 1 << 25, 1 << 26, 1 << 27, 1 << 28, 1 << 29, 1 << 30 };
I guess this SHIFTS[]
array is used in data partitioning.
Why was the left shift operator used inside the array declaration?
left shifting an integer “x” with an integer “y” denoted as ‘(x<<y)’ is equivalent to multiplying x with 2^y (2 raised to power y).
right shifting an integer “x” with an integer “y” denoted as ‘(x>>y)‘ is equivalent to dividing x with 2^y.
Since the final value of the array would be like the following, why just not declare it as this?
static const uint32_t SHIFTS[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216,
33554432, 67108864, 134217728, 268435456, 536870912, 1073741824};
I tried to compute each shift operation on each element and found the final array value, but I could not figure out why someone would want to declare an array with the left shift operator.
CodePudding user response:
The compiler will almost certainly generate the same static data for the two definitions. The difference is readability to human users.
The declaration using the shifts actually presents a human-readable intent, that the array ought to be full of consecutive powers of two.
In fact, it's sufficiently readable that many readers can verify that the shifts are correct and follow the intended pattern, with only a quick skim. This makes the code less error-prone, easier to extend in the future (suppose you had to handle shifts up to 2^63 in a later version?), and otherwise easier to read.
On the other hand, readers are not expected to remember that 1073741824 == 2^30, or many other powers of two for that matter. If I had to work with the second sample of code, I'd have to spend quite a bit of effort keeping track of all of the values, calculating them with a calculator, etc.