I was reading one of the application of "Unions" of creating mixed data types. Example
typedef union {
int x;
float y;
}mix;
mix arr[100];
Each element of array arr[100]
can store either a int
or a float
type value. But suppose I want to take a input from user and store it in arr[ ]
and I won't know that either user is going to enter a float
or an int
value. So I don't know which statement from the following I should choose to store that input from user.
1.scanf ("%d",&arr[0].x);
OR
2.scanf ("%f",&arr[0].y);
And similar problem arises when I want to print that value.
I know I can solve this problem using a "tag field". So I can do it as
#include <stdio.h>
typedef union {
int x;
float y;
}mix;
mix arr[100];
int main ()
{
int k; // tag field
puts("Mention 1 if you want to enter integer and 0 if you want to enter float value");
scanf ("%d",&k);
if (k)
{
scanf ("%d",&arr[0].x);
printf ("%d is the entered integer value\n",arr[0].x);
}
else
{
scanf ("%f",&arr[0].y);
printf ("%f is the entered float value\n",arr[0].y);
}
}
But here user is telling the type of data he is gonna enter(with the help of 0 or 1). I want to know: Is there any way in C language that compiler can automatically detect the type of data user is entering and according run either 1st or 2nd scanf
statement without help of user? OR Is there any predefined function present in library for doing that?
Also tell if you have any another intresting way of doing this program.