Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unset a variable in C to allow usage of the same name with different datatype later on?

Tags:

c

variables

unset

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 ?

like image 702
AssemblerGuy Avatar asked Dec 06 '10 23:12

AssemblerGuy


People also ask

Can I redefine a variable in C?

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.

Can you define a variable twice in C?

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.

What is variable list the restrictions on the variable names in C?

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.

What is &Var in C?

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.


2 Answers

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'
 }
like image 125
Justin Spahr-Summers Avatar answered Sep 20 '22 09:09

Justin Spahr-Summers


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.
like image 22
nmichaels Avatar answered Sep 21 '22 09:09

nmichaels