Why does it happen? The code works and generates no warnings with GCC 4.7 on Linux and MSVC++ 2010 on Windows. Yet, on ideone.com it crashes with SIGILL
. Is undefined behavior involved here?
#include <iostream>
#include <cstdarg>
using namespace std;
enum types
{
INT,
DOUBLE,
CHAR,
STRING
};
struct mt
{
types type;
union
{
int i;
double d;
char c;
const char *s;
} val;
mt(int i)
: type(INT)
{
val.i = i;
}
mt(double d)
: type(DOUBLE)
{
val.d = d;
}
mt(char c)
: type(CHAR)
{
val.c = c;
}
mt(const char *s)
: type(STRING)
{
val.s = s;
}
};
void print(int n, ...)
{
va_list ap;
va_start(ap, n);
for (int i = 0; i < n; i++)
{
mt x(va_arg(ap, mt));
switch (x.type)
{
case INT:
cout << x.val.i << endl;
break;
case DOUBLE:
cout << x.val.d << endl;
break;
case CHAR:
cout << x.val.c << endl;
break;
case STRING:
cout << x.val.s << endl;
break;
}
}
va_end(ap);
}
int main()
{
print(4, mt(2), mt(4.2), mt('a'), mt("Hello"));
}