help on typedefs - basic c/c++
i have been going through some code and came across a statement that somehow disturbed me.
typedef GLfloat vec2_t[2];
typedef GLfloat vec3_t[3];
开发者_StackOverflow中文版
From my perspective, a statement such as
typedef unsigned long ulong;
Means that ulong is taken to mean unsigned long
Now, can the statement below mean that vec2_t[2] is equivalent to GLfloat??typedef GLfloat vec2_t[2];
Most likely, Probably its not the intended meaning. I would appreciate it if someone clears this up for me. Thanks
Basically a typedef
has exactly the same format as a normal C declaration, but it introduces another name for the type instead of a variable of that type.
In your example, without the typedef, vec2_t
would be an array of two GLfloat
s. With the typedef it means the vec2_t
is a new name for the type "array of two GLfloat
s".
typedef GLfloat vec2_t[2];
This means that these two declarations are equivalent:
vec2_t x;
GLfloat x[2];
C declaration syntax can be confusing, but you only need one simple rule: read from the inside-out. Once you do that, just understand typedef creates another name (an alias) for a type.
The inside is the declared-identifier (or where it would go if missing). Examples:
T a[2]; // array (length 2) of T
T* a[2]; // array (length 2) of pointer to T ([] before *)
T (*p)[2]; // pointer to array (length 2) of T (parens group)
T f(); // function returning T
T f(int, char*); // function of (int, pointer to char) returning T
T (*p)(int); // pointer to function of (int) returning T
T (*f(char, T(*)[2]))(int);
// f is a function of (char,
// pointer to array (length 2) of T)
// returning a pointer to a function of (int)
// returning T
typedef T (*F(char, T(*)[2]))(int);
// F is the type:
// function of (char,
// pointer to array (length 2) of T)
// returning a pointer to a function of (int)
// returning T
// (yes, F is a function type, not a pointer-to-function)
F* p1 = 0; // pointer to F
T (*(*p2)(char, T(*)[2]))(int) = 0; // identical to p1 from the previous line
In your case, vec2_t
is an array of 2 GLfloats and vec3_t
is an array of 3 GLfloats. You can then do stuff like:
vec2_t x;
// do stuff with x[0] and x[1]
When you want to create a typedef-name vec2_t
for an array type GLfloat[2]
, the proper syntax would be not
typedef GLfloat[2] vec2_t;
(as a beginner might expect), but rather
typedef GLfloat vec2_t[2];
I.e. the general structure of the syntax here, as it has already been said, is the same an in a variable declaration.
It means that vec2_t
is an array of 2 GLfloat
and that vec3_t
is an array of 3.
More info
The intent would be clearer if C syntax allowed it to be written as
typedef GLfloat[2] vec2_t;
typedef GLfloat[3] vec3_t;
But that's not valid syntax.
精彩评论