Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C typedef const argument

typedef float vec3[3];

void test(vec3 const vptr) {
    *vptr = 1.f; // error: assignment of read-only location
    vptr[0] = 1.f; // error: assignment of read-only location
    vptr++; // no error
}

Is

vec3 const vptr

the same as

const vec3 vptr

for all typedefs? Is there any difference between last two? I thought

vec3 const vptr <==> float* const vptr // a constant pointer to an object
const vec3 vptr <==> const float* vptr // a pointer to a constant object
??? <==> const float* const vptr // a constant pointer to a constant object
like image 763
dizcza Avatar asked Apr 02 '17 14:04

dizcza


1 Answers

This typedef

typedef float vec3[3];

defines an alias for the array type float[3]

This declaration of the parameter

vec3 const vptr

declares vptr as having array type const float[3].

Function parameters that are specified as having array types are adjusted to pointers to objects of the array element types.

So this declaration

vec3 const vptr

is adjusted to the type const float *vptr. That is it is a non constant pointer to a constant object.

This relation

vec3 const vptr <==> float* const vptr // a constant pointer to an object

is wrong. And this statement

vptr++; // no error

confirms that.

You can not get this declaration

const float* const vptr 

using this typedef

typedef float vec3[3];
like image 142
Vlad from Moscow Avatar answered Nov 08 '22 23:11

Vlad from Moscow