Search code examples
c++typedef

Typedef declaration in the form `int typedef my_int;`


To declare my_int as a type alias for int we can write:

typedef int my_int;   // (1)

Curiously, the following also seems to define an int alias:

int typedef my_int;   // (2)

I have never seen such syntax before. Why does it work?


Solution

  • My reasoning after reading C++ reference is this: (1) and (2) are declarations of the form

    specifiers-and-qualifiers declarators-and-initializers;
    

    with specifiers-and-qualifiers being either typedef int or int typedef.

    The order of specifiers and qualifiers doesn't matter, and both (1) and (2) are valid declarations of a type alias. For example, to define an alias for const int we can, in principle, use any of these 6 combinations:

    typedef int const my_cint;
    typedef const int my_cint;
    int typedef const my_cint;
    const typedef int my_cint;
    int const typedef my_cint;
    const int typedef my_cint;