Topic: Summary Code
Author: No.Email@Address.ucar.edu ("Tom s")
Date: Tue, 23 May 2006 21:23:59 GMT Raw View
To summarise, I'd like to see the following program output the following=20
on all platforms:
"Program is absent of Undefined Behaviour. YIPPIE!"
(I wonder if anyone can find a platform where it wouldn't? I doubt it.)
#include <iostream>
#include <cstdlib>
bool has_printed_UB =3D false;
void PerformUndefinedBehaviour()
{
std::cout << "Undefined Behaviour!\n";
has_printed_UB =3D true;
}
struct Monkey {
union {
double array[5];
struct { double a, b, c, d, e; };
struct { int f; int g; };
};
char h;
double i;
double j;
};
int main()
{
Monkey obj;
/* First demonstrate that the struct elements correspond
to the array elements */
obj.a =3D 1;
obj.b =3D 2;
obj.c =3D 3;
obj.d =3D 4;
obj.e =3D 5;
if ( *obj.array !=3D 1 ||
obj.array[1] !=3D 2 ||
obj.array[2] !=3D 3 ||
obj.array[3] !=3D 4 ||
obj.array[4] !=3D 5 ) PerformUndefinedBehaviour();
/* Now demonstrate that the first member of a POD union or POD struct
has the same address as the actual union/struct. (Yes I realise
that the Standard already guarantees this.) */
int * p =3D reinterpret_cast<int*>(&obj);
*p =3D 67;
*++p =3D 54;
if ( !( 67 =3D=3D obj.f && 54 =3D=3D obj.g ) ) PerformUndefinedBehavi=
our();
/* Now show that i and j are contiguous: */
if ( sizeof(double) !=3D
reinterpret_cast<const char*>(&obj.j)
- reinterpret_cast<const char*>(&obj.i)
) PerformUndefinedBehaviour();
if (!has_printed_UB)
std::cout << "Program is absent of Undefined Behaviour. YIPPIE!
\n";
std::system("PAUSE");
}
-Tom=E1s
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]