Why call sizeof operator with two arguments?

三世轮回 提交于 2019-12-03 11:11:19

On further research, I discovered that this is behavior specific to the WindRiver Diab compiler. Please see the EDIT in the question for details.

It looks to me like a simple application of the comma operator, which evaluates its first argument, throws away the result, then evaluates its second argument.

In this case, it's determining whether the literal 2 has size 4. The "var" part is irrelevant.

Looks like a red herring. My guess is that you are accidentally using the comma operator and sizeof is being applied to the last value.

As mentioned, the comma operator is being applied and sizeof is returning the size of an integer literal. Offhand this looks like an error on the author's part, but there could be some sinister coding happening.

sizeof expressions are not evaluated so they can be used for a number of tricky things. One example is to provide a reference for an otherwise unreferenced variable without causing the compiler to generate any code. See this article on creating a better assert macro for an example. Alexandrescu has some other examples of sizeof trickery in Modern C++ Design, if memory serves. It's possible, but not likely, that one of these non-obvious usages is intended.

Whatever the usage, if it's not commented in this situation then it's clearly not worth the trade-off in readability and should be changed.

Important disclaimer: Below code is pseudo code. The arguments to sizeof are never actually be evaluated, with the meaning of "executed", it is always a compile time construct (and therefore one of the tools preferred by template authors, like enums).

note that I borrowed auto below from C++ (0x); it tells the compiler to deduce the type from the initializer expression and makes the examples a bit simpler

What many don't know is that you can invoke sizeof validly like this:

auto s = sizeof int;

I.e., no parentheses needed. Therefore, if you pass (x,y) to sizeof, it is equivalent to

auto c = (x,y);
auto s = sizeof c;

or just

auto c = x,y;
auto s = sizeof c;

x,y is a sequence, where each part is evaluated left to right, and the sequence gets the value of the last part, in this case this is y. So, the original code is roughly equivalent to

auto s = sizeof y;

So it looks to me that the compiler in question does something really, really braindead, in that it introduces an extension that also compiles on other compilers, but with a totally different meaning. This is bad.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!