Reputation: 5731
I want to call the same variable with a different name, how can I assign it an alias?
Do I stick to using a macro, like
#DEFINE Variable Alias
I'm currently doing it in C using functions as the method for renaming.
So given the variable: int signal
I'd do the following
int Temperature(){return signal;}
Upvotes: 10
Views: 39214
Reputation: 105
C++, something along the lines of:
struct A{
union{
int temperature;
int sametemperature;
};
};
A a;
a.temperature = 2;
a.sametemperature = 3;
Depending on compiler and compatibility flags, you can get away with this in plain C. In short try leveraging anonymous unions. Question is old but, I was looking for an answer to the same question and realised there's a solution without pointers/references or macros.
Upvotes: 5
Reputation: 279
An alternative to Eric Lippert's answer:
int a;
int * const b = &a;
Now *b
is the same as a
it can not be made to point to anything else, the compiler will not generate additional code to handle a
or *b
, neither reserve space for a pointer.
Upvotes: 14
Reputation: 1397
I think that #define doesn't design for this use case. Firstly because it is a preprocessor directive which is processed before the program get compile. You lose a chance for the compiler to give meaningful warning and you might end up having a strange error or warning that is hard to fix.
Pointer seem to work but you need to use a * (dereferencing operator) every time which is dangerous, harder to read and if you miss the * you might get a segmentation fault or similar memory error.
Try post some code and we might found a proper solution that suit your need.
Upvotes: 1
Reputation: 660038
You say
int a, *b;
b = &a; // *b is now an alias of a
I like to think of a pointer as something that gives you a variable when you star it, and the ampersand as the alias-making operator.
Upvotes: 9
Reputation: 7631
Why not just pass it as a parameter to the function and use the appropriate name in the function argument? I don't think #define is a good idea as it may lead to obfuscation. That is in C. Of course you can use aliases in C++.
Upvotes: 4
Reputation: 227400
The way to provide an alias for a variable in C++ is to use references. For example,
int i = 42;
int& j = i; // j is an alias for i
const int& k = j; // k is an alias for i. You cannot modify i via k.
Upvotes: 34