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 ?
In C, you cannot redefine an existing variable. For example, if int my_var = 2 is the first definition, your program won't compile successfully if you try redefining my_var as int my_var = 3 . However, you can always reassign values of a variable.
Save this question. Show activity on this post. int a; means both declaration and definition, but we know that defining a variable more than once is not allowed.
Variable names in C are made up of letters (upper and lower case) and digits. The underscore character ("_") is also permitted. Names must not begin with a digit. Unlike some languages (such as Perl and some BASIC dialects), C does not use any special prefix characters on variable names.
Address in CIf you have a variable var in your program, &var will give you its address in the memory. We have used address numerous times while using the scanf() function. scanf("%d", &var); Here, the value entered by the user is stored in the address of var variable. Let's take a working example.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With