Home > OS >  What is an Alias in C ?
What is an Alias in C ?

Time:03-14

I know how pointers work:

int a=10;
int* ptr=&a;

cout<<ptr; gives me the address of a stored in the ptr cout<<*ptr gives me the value written on the address stored in ptr 'cout<<&ptr;' gives me the address of the ptr that I created.

So, what does an alias mean? Can someone explain it using an example, since I can't find any on the internet?

CodePudding user response:

You can think of the term alias to be a substitution for the phrase "another name for" . Following examples should clarify this:

using customint = int; //customint is "another name for" int
using customdouble = double; //customdouble is "another name for" double

int i = 0;
int &refI = i; //refI is "another name for" i

We generally don't use the term alias when talking about(in relation to) pointers.

In the above snippet, we can say that customint is an alias for int. We can also say this as customint is another name for int.

Similarly for others.

CodePudding user response:

"To alias" more or less means "to refer to". *ptr aliases a.

I haven't heard "alias" being used as a noun in relation to pointers.

CodePudding user response:

Aliases and pointers address (forgive the pun) completely different issues (but see below). An alias allows you to define your own name for an existing, predefined type of variable. In C (since C 11), you can use the using keyword to define an alias:

using MYINT = int;

After the above code, you can use the name MYINT (the alias) anywhere you would otherwise use an int declaration; thus, the following two lines would then be equivalent:

int i;
MYINT i;

Before C 11 (and even in plain C), aliases are also available, using the typedef keyword:

typedef int MYINT;

However, what may be confusing you is the use of the term "aliasing" (or "strict aliasing rules") when referring to pointers. These terms refer to the rules required when attempting to access one type of object through a pointer that is (formally) the address of a different type of object. This subject has been discussed in numerous posts on Stack Overflow; for example: What is the strict aliasing rule?

  • Related