A
arnuld
I got this question in C while googling for top c interview questions.
There are several things which I could not comprehend:
#include <stdio.h>
#include <string.h>
int main(void)
{
typedef union
{
int a;
char b[10];
float c;
} uni;
uni x,y = {100};
x.a = 50;
strcpy(x.b,"hello");
x.c = 21.50;
printf("Union x : x.a = %d, x.b = %s, x.c = %f \n",x.a,x.b,x.c );
printf("Union y : %d %s %f \n",y.a,y.b,y.c);
return 0;
}
===================== OUTPUT =========================
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra interview-1.c
/home/arnuld/programs/C $ ./a.out
Union x : x.a = 1101791232, x.b = , x.c = 21.500000
Union y : 100 d 0.000000
/home/arnuld/programs/C $
Q1: As per C90 (or C89, are they same ?) can we define a struct inside
another function ?
Q2: uni x,y = {100} is legal because it compiles. What exactly this line
means for value of y ?
Q3: why x.b is not printing anything even when something was copied into
it ? Why x.a has some strange value instead of 50.
Q4: Values in y are garbage, so it will print anything. Right ?
There are several things which I could not comprehend:
#include <stdio.h>
#include <string.h>
int main(void)
{
typedef union
{
int a;
char b[10];
float c;
} uni;
uni x,y = {100};
x.a = 50;
strcpy(x.b,"hello");
x.c = 21.50;
printf("Union x : x.a = %d, x.b = %s, x.c = %f \n",x.a,x.b,x.c );
printf("Union y : %d %s %f \n",y.a,y.b,y.c);
return 0;
}
===================== OUTPUT =========================
/home/arnuld/programs/C $ gcc -ansi -pedantic -Wall -Wextra interview-1.c
/home/arnuld/programs/C $ ./a.out
Union x : x.a = 1101791232, x.b = , x.c = 21.500000
Union y : 100 d 0.000000
/home/arnuld/programs/C $
Q1: As per C90 (or C89, are they same ?) can we define a struct inside
another function ?
Q2: uni x,y = {100} is legal because it compiles. What exactly this line
means for value of y ?
Q3: why x.b is not printing anything even when something was copied into
it ? Why x.a has some strange value instead of 50.
Q4: Values in y are garbage, so it will print anything. Right ?