Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign to a variable an alias

Tags:

c++

c

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;}
like image 856
Iancovici Avatar asked Jun 10 '13 14:06

Iancovici


3 Answers

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.
like image 62
juanchopanza Avatar answered Oct 13 '22 21:10

juanchopanza


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.

like image 30
Eric Lippert Avatar answered Oct 13 '22 21:10

Eric Lippert


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.

like image 37
LuisF Avatar answered Oct 13 '22 21:10

LuisF