Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef equivalence for a pointer to struct

Tags:

c++

typedef

I got this implementation of a struct:

struct NodoQ {
  Etype elem;
  NodoQ *sig;
};

Is this code below,

typedef NodoQ *PtrNodoQ;
PtrNodoQ ppio, fin;

the same as this one?

NodoQ* ppio;
NodoQ* fin;
like image 330
HoNgOuRu Avatar asked Apr 23 '15 21:04

HoNgOuRu


2 Answers

Is this code below,

typedef NodoQ *PtrNodoQ;
PtrNodoQ ppio, fin;

the same as this one?

NodoQ* ppio;
NodoQ* fin;

Yes, it's resulting in the exactly same pointer types for ppio and fin.


As for your comment

"I didn't try cause I got the second option everywhere in my code, and just didn't want to loose some time... "

You can easily test it:

void foo(PtrNodoQ p) {
}

void bar(NodoQ* p) {
    foo(p);
}

and

void baz() {
    NodoQ n;
    foo(&n);
    bar(&n);
}

compile all perfectly fine, without invalid type conversion warnings or errors.


Also you could have found the answer quickly in this excellent reference (emphasis mine):

The typedef-names are aliases for existing types, and are not declarations of new types. Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again. Typedef names are only in effect in the scope where they are visible: different functions or class declarations may define identically-named types with different meaning.

like image 125
πάντα ῥεῖ Avatar answered Oct 05 '22 09:10

πάντα ῥεῖ


In case you wanted the standardese, [dcl.typedef] states that:

A name declared with the typedef specifier becomes a typedef-name. Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in Clause 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) or enum declaration does. [ Example: after

typedef int MILES, *KLICKSP;

the constructions

MILES distance;
extern KLICKSP metricp;

are all correct declarations; the type of distance is int and that of metricp is “pointer to int.” —end example ]

In your case, after

typedef NodoQ *PtrNodoQ;

The types PtrNodoQ and Node* are exactly the same and can be used interchangeably from there on out. The declarations NodoQ* ppio; and PtrNodoQ ppio; are exactly equivalent.

like image 33
Barry Avatar answered Oct 05 '22 09:10

Barry