C++: Is 2 + x + 1 the same as 3 + x?
c++, google-chrome
Solution
Yes, it does evaluate the same way.
Presumably the authors wrote it that way to make it clearer how their array was laid out -- i.e. that it contained 2 bytes for one thing, then 2 pointers, and then 1 more byte after that. (Actually I'm not sure why they chose to use the sizeof() operator in this case, since the length of a string representation of a pointer isn't the same as the pointer's in-memory width)
The compiler will optimize away the math at compile time, so performance isn't effected; it's just to keep other programmers from having to figure out where the 3 came from.
Problem
This following snippet of code from the Chromium source caught my eye (see line 155 here): ``` std::string PrintPreviewUI::GetPrintPreviewUIAddress() const { // Store the PrintPreviewUIAddress as a string. // "0x" + deadc0de + '\0' = 2 + 2 * sizeof(this) + 1; char preview_ui_addr[2 + (2 * sizeof(this)) + 1]; base::snprintf(preview_ui_addr, sizeof(preview_ui_addr), "%p", this); return preview_ui_addr; } ``` Doesn't `2 + (2 * sizeof(this)) + 1` evaluate to `3 + 2 * sizeof(this)`? Why did the authors choose to write the expression this way?