Iancovici
Iancovici

Reputation: 5731

How to assign to a variable an alias

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

In summary:

  1. I prefer to apply it in C
  2. I have a signal which can be more than one type of variable (temperature, distance, etc..)
  3. I want to assign more than one alias to that signal

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

Answers (6)

Kalibr
Kalibr

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

LuisF
LuisF

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

Nuntipat Narkthong
Nuntipat Narkthong

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

Eric Lippert
Eric Lippert

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

Sid
Sid

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

juanchopanza
juanchopanza

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

Related Questions