Hello,
I've been having trouble trying to duplicate this program.
My output differs from the sample output I was given for homework. I don't understand whats wrong with my code.
void displayUnion( iUnion );
union integer_union
{
char c;
short s;
int i;
long l;
};
typedef union integer_union iUnion;
int main()
{
iUnion value;
/* char */
printf( "Please enter a char: " );
scanf( "%c", &value.c );
displayUnion( value );
/* short */
printf( "%s", "Please enter a short: " );
scanf( "%hd", &value.s );
displayUnion( value );
/* int */
printf( "%s", "Please enter an int: " );
scanf( "%d", &value.i );
displayUnion( value );
/* long */
printf( "%s", "Please enter a long: " );
scanf( "%ld", &value.l );
displayUnion( value );
/* ending code */
system( "pause" );
return 0;
} /* end main */
/* prints each variable in the union */
void displayUnion( iUnion passedIn )
{
printf( "char c = %c\n", passedIn.c );
printf( "short s = %hd\n", passedIn.s );
printf( "int i = %d\n", passedIn.i );
printf( "long l = %ld\n\n", passedIn.l );
} /* end function displayUnion */
My result:
Please enter a char: a
char c = a
short s = -13215
int i = -858993567
long l = -858993567
Please enter a short: 1
char c = ☺
short s = 1
int i = -859045887
long l = -859045887
Please enter an int: 1
char c = ☺
short s = 1
int i = 1
long l = 1
Please enter a long: 1
char c = ☺
short s = 1
int i = 1
long l = 1
Press any key to continue . . .
Sample output result:
Please enter a char: a
char c = a
short s = 14177
int i = 1982543713
long l = 1982543713
Please enter a short: 1
char c = ☺
short s = 1
int i = 1982529537
long l = 1982529537
Please enter an int: 1
char c = ☺
short s = 1
int i = 1
long l = 1
Please enter a long: 1
char c = ☺
short s = 1
int i = 1
long l = 1
Press any key to continue . . .
Maybe something is wrong with my displayUnion() function?
The problem here is the numbers don't seem to match and I have no idea why even though I believe my code looks correct.
Anyways, help please! ^^