Is this a suitable use of const qualifiers in C?

I have a simple vector implementation in C that contains a void * array. It is up to the user to take care of the actual type.

I want to “promise” that the vector will not change its contents, so I store the data as:

Struct _Vector{
    UInt32 used;
    UInt32 size;
    const void** arr;
};

I don’t know if he considered "overdoing" the rule of his constant, but I try to maintain constant correctness with my accessories / modifiers:

void vector_add(Vector *v, const void* const elem);   
void vector_set(Vector *v, const UInt32 idx, const void* const elem);

When I return an element from a vector, it is a pointer to user data, so I let the user change the displayed data by discarding the constant in the internal array.

void* vector_get(const Vector *v, const UInt32 idx){
    if ( idx >= v->used ) 
        exitAtError("Vector","Array out of bounds");
    return (void*)v->arr[idx];
}

, const void *, void *. , , , , , .

const? , const , . , , , , , const .

+4
3

"",

C. . , , , . , .

, "" , /:

const, const -. , .

, , , .

. . const - .

const, , Vector , . , , . , const - , , , , const . , , (, , ).

const -qualifying . , , const-correctness , const , const.

+2

, , const . :

const int x = 5;
vector_add(&v, &x);

int *p = vector_get(&v, 0);
*p = 6;   // oops

const void *. , const.

, , void *, - const void *.

+1

const, , C , , [im] . . - const- , , get(). , .

, , , const. .

+1

All Articles