C Collections

cvector · Section 3

cvec_push

cvec_push - push an element onto the vector (type-inferred)

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_push(v, new_elem);

Type-inferred wrapper for cvector_push_back(). new_elem is converted to
the declared element type of v by an ordinary C assignment, exactly as
"T tmp = new_elem;" would do, and the converted value is copied into the
vector. What gets pushed is the result of a plain C assignment, not the
raw byte representation of new_elem. The macro calls ccol__fatal_err()
when cvector_push_back() fails.
 
For an array element type, such as char[64], new_elem is an array or a
string literal; the macro zero-fills the element and copies the bytes of
new_elem into it, up to the smaller of the two sizes. Passing a pointer as
new_elem for such a type is a compile error, since the macro can't see the
size of what it points at.
 
The macro never takes the address of new_elem. It copies the value into a
temporary of the element type first, so a literal, a computed expression
or a struct value returned by a function works just as well as a
variable.

v         Vector to push onto
new_elem  The element. It can be a variable, a literal or any
          expression, for example a struct value that a function
          returns

A failure stops the program.
 
The value of new_elem is converted to the declared element type of v the
same way a plain C assignment converts it. An int literal pushed into a
cvec_construct(v, long) becomes a long, and a float pushed into a
cvec_construct(v, int) is truncated to an int, as with
"int x = some_float;". The raw bit pattern of new_elem is never copied
into an element of a different type, even when the two types have the
same size. A new_elem whose type has no implicit conversion to the
declared element type of v is a compile error here; such a value is
never silently reinterpreted.
 
new_elem may alias into the backing buffer of v, for example when it is
cvec_at(v, i). The value is read into a private temporary that doesn't
alias before v is touched, so a capacity growth started by this call can
never invalidate it.
 
With GCC 11 or later every padding byte of the temporary is zeroed before
the push, so a struct element is stored with zero padding, which
cvec_find(3) relies on. With a compiler that has no
__builtin_clear_padding, such as Clang, the padding bytes of the stored
element are unspecified.

cvec_construct(vec, int);
int x = 42;
cvec_push(vec, x);
cvec_destroy(vec);

cvector_push_back(3)