Jens Gustedt's Blog

May 19, 2012

type generic functions taking pointers or arrays

Filed under: C11, language, P99 — Jens Gustedt @ 14:26

Every C programmer knows about the implicit conversion an array object A undergoes in most contexts: it is converted to a pointer to its first element, as if the programmer had written `&A[0]`. The technical term of the standard for that is “lvalue conversion”, and the corresponding section describes what precisely is going on when an object (an lvalue) is evaluated for its contents (the rvalue).

One particular place where this conversion takes place is when an array is passed as an argument to a function. So in that case all additional information about the array, in particular its length, is not made available to the function. One could always pass the size of the array (sizeof A) as additional argument to the function, but this then would always require to pass this information also in case the function is called with what its interface suggest, just a pointer. In this post I will describe a new possibility that is provided by the _Generic keyword in C11 that allows us to create type generic interfaces that knows how to distinguish between the case being called with an array or with a pointer as an argument.
(more…)

Advertisements

Create a free website or blog at WordPress.com.