How can I unset a variable in C to allow usage of

2019-06-19 16:30发布

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 ?

6条回答
神经病院院长
2楼-- · 2019-06-19 17:10

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.
查看更多
一夜七次
3楼-- · 2019-06-19 17:13

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!

查看更多
萌系小妹纸
4楼-- · 2019-06-19 17:22

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;
}
查看更多
狗以群分
5楼-- · 2019-06-19 17:29

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'
 }
查看更多
霸刀☆藐视天下
6楼-- · 2019-06-19 17:32

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;
查看更多
Summer. ? 凉城
7楼-- · 2019-06-19 17:36

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 :)

查看更多
登录 后发表回答