AssemblerGuy
AssemblerGuy

Reputation: 623

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

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 ?

Upvotes: 5

Views: 11637

Answers (5)

Ferruccio
Ferruccio

Reputation: 100718

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!

Upvotes: 0

nmichaels
nmichaels

Reputation: 51009

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.

Upvotes: 2

pmg
pmg

Reputation: 108988

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;
}

Upvotes: 0

Daniel Bingham
Daniel Bingham

Reputation: 12914

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;

Upvotes: 1

Justin Spahr-Summers
Justin Spahr-Summers

Reputation: 16973

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'
 }

Upvotes: 15

Related Questions