C Collections

cvector · Section 3

cvec_redeclare

cvec_redeclare - declare the companion type variables again for a vector from another scope

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_redeclare(v, type);

Declares the two companion type variables for v that the type-dispatching
macros read. It doesn't declare v itself and doesn't touch the vector
that v names. Use it wherever a cvec arrives from somewhere else, most
often a function parameter but also, for example, a struct member copied
into a local; after it, cvec_at(3), cvec_push(3) and the other macros work
on that handle.
 
The companion variables carry type information only. Nothing reads them
at run time, they are marked unused and they cost nothing. The value
companion carries the element type, which the type-dispatching macros use
to type their results and to size what they copy. The key companion
carries size_t, the type of the index that a vector iterator reports
through ccol_iter_key_ptr(3).
 
The type you give is a statement about the vector, not a request to
change it. Nothing checks it against the element size the vector was
created with, so a different type reinterprets the stored bytes as that
type.

v     Name of the vector variable that is in scope already
type  Element type that the vector holds
      Any type name works, a function pointer type such
      as void (*)(int) and an array type such as int[4]
      included. For an array element type, give
      cvec_push(3) an array or a string literal, whose
      bytes the macro copies into the element

None. The macro expands to declarations, not to an expression.

The macro expands to a pair of declarations and needs a semicolon at the
end of the call, so it goes where declarations are legal and can't be the
body of an if or a loop without braces.
 
v is pasted into the names of the companion variables, so it must be a
plain identifier. Nothing named v is declared, which means the handle has
to be in scope already. No vector is created or destroyed.
 
Using it twice for the same v in the same scope declares the same names
again, and the code doesn't compile.

The type must be the real element type of the vector. A wrong type gets no
diagnostic from the compiler, and the type-dispatching macros then read
and write the vector's bytes as that type; if its size is different they
also compute element offsets that don't match the vector's own.

void process(cvec vec) {
    cvec_redeclare(vec, int);
 
    for (size_t i = 0; i < cvec_size(vec); i++) {
        printf("%d\n", cvec_at(vec, i));
    }
}

cvec_declare(3), cvec_construct(3), cvec_at(3), cvec_push(3), cvec_size(3), ccol_iter_key_ptr(3)