Typedefs help - basic c / c ++

I was looking at some code and came across an expression that somehow bothered me.

typedef GLfloat vec2_t[2]; typedef GLfloat vec3_t[3]; 

From my point of view, such a statement as

 typedef unsigned long ulong; 

Means that ulong is accepted to designate unsigned long
Now can the statement below mean that vec2_t [2] is equivalent to GLfloat ??

 typedef GLfloat vec2_t[2]; 

Most likely, this is probably not the intended meaning. I would appreciate it if someone clarifies this for me. Thanks

+4
source share
6 answers

Basically, typedef has exactly the same format as a regular C declaration, but it introduces a different name for the type instead of a variable of that type.

In your example, without typedef, vec2_t will be an array of two GLfloat s. With typedef, this means that vec2_t is the new name for an array of type two GLfloat s.

 typedef GLfloat vec2_t[2]; 

This means that these two declarations are equivalent:

 vec2_t x; GLfloat x[2]; 
+15
source
Syntax syntax

C can be confusing, but you only need one simple rule: read from the inside out . Once you do this, just know that typedef creates a different name (alias) for the type.

The inner part is the declared identifier (or where it will go if absent). 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 
+2
source

In your case, vec2_t is an array of two GLfloats and vec3_t is an array of 3 GLfloats. Then you can do things like:

 vec2_t x; // do stuff with x[0] and x[1] 
+1
source

If you want to create typedef-name vec2_t for the GLfloat[2] array type, the correct syntax will not be

 typedef GLfloat[2] vec2_t; 

(as a beginner might expect), but rather

 typedef GLfloat vec2_t[2]; 

those. the general syntax structure here, as already mentioned, is the same in a variable declaration.

+1
source

This means that vec2_t is an array of 2 GLfloat and that vec3_t is an array of 3.

Additional Information

0
source

The intention would be clearer if the C syntax allowed it to be written as

 typedef GLfloat[2] vec2_t; typedef GLfloat[3] vec3_t; 

But this syntax is not valid.

0
source

All Articles