I was looking at some C++ networking code. When I went to find out how large the buffer was, I found something like this:
static const uint32_t MAX_COMMAND_BUFFER =
sizeof(struct S1) | sizeof(struct S2) | sizeof(struct S3) |
sizeof(struct S4) | sizeof(struct S5) | sizeof(struct S6);
I believe the basic idea here is that the buffer can contain any one of these 6 structs. This is declared at an outer scope, so its available for things like a later outer-scope uint8_t
array size.
Now normally here I'd expect to see something using either the std::max() function, or the tertinary operator to calculate the exact size of the largest of those 6 structs. I've never seen the above idiom before, and had to stop to even convince myself it would work.
So since I'm new at this, I'd like in general to know how valid this is, and what are the benefits and drawbacks of doing it.
What I can see is -
pro:
- It should always give you a size at least as large as your largest struct size. Which is all you really need if space isn't at a premium.
- It appears to be calculable at compile time.
- It should work even with very old C++ (or even C) compilers.
con:
- It may make the size nearly twice as large as necessary.
- It makes it much more difficult for a human to figure out offline exactly how large the buffer is.
- Its weird / unexpected.