I want to use the same variable name with a different datatype in C program without casting.
I really wanna do that don't ask why.
So how can I do that ?
And how can I handle the error if this variable doesn't exist while doing prophylactic unsetting ?
You can't. The closest you can get is creating separate scopes and using the same variable name in them:
{
int val;
// do something with 'val'
}
{
double val;
// do something with 'val'
}
If you want the same memory to be referenced with two different types, use a union. Otherwise, know that what follows is a terrible idea.
int foo;
float bar;
#define MY_NAME foo
// use MY_NAME as an int.
#undef MY_NAME
#define MY_NAME bar
// use MY_NAME as a float.
I don't believe this is possible in C. The only way I can imagine doing this would be to write your program such that the two different variables exist in completely different scopes. Such as when you use them in different functions. Other than that, you're stuck with your first variable, pick a different name.
My suggestion -- if you absolutely require then to exist in the same scope -- would be to prefix the name with a type identifying letter, so:
int iVal;
double dVal;
use a void pointer and cast appropriately ...
by now you should be asking "WTF?" - and yes, that's what you should have been asking yourself when you came up with the idea to re-type your variables :)
When you define a variable with a name that already exists, the new definition "hides" the old one.
#include <stdio.h>
int main(void) {
int variable = 42;
printf("variable is an int and its value is %d\n", variable);
{
double variable = -0.000000000000003;
printf("variable is a double and its value is %g\n", variable);
}
{
FILE *variable = NULL;
printf("variable is a FILE * and its value is NULL :-)\n");
}
printf("variable is an int again and its value is, again, %d\n", variable);
return 0;
}
You can't change the type of a variable in C. You can use a little preprocessor trickery to get the illusion of what you want. i.e.
int myvar = 10;
// code using myvar as an int
#define myvar _myvar
char *myvar = "...";
// code using myvar as a char*
That being said, I cannot discourage this strongly enough. Don't do it!