niedziela, 12 czerwca 2016

Old dog,old tricks (in C++)

Compile time safety, compile time error handling - all about typesystem, constness, ...

C-array safety

If function uses constant length array it is tempting to use:


void f(int t[3])
{
...
t[2] = ...;
}

...

int t[3];
f(t);


as array size is merely for human-programmer, it is possible to use:


int t[4];
f(t);


which perhaps is ok (but not nice).
But it is also possible to do


int t[2];
f(t);


Which for sure is wrong.

Solution to ensure strict array size is:


void f(int (&t)[3])
{
...
}


Now only three elements arrays are allowed.
BTW - above construct is frequently used for C-array handling in templates.

Brak komentarzy:

Prześlij komentarz