Sonntag, 7. Dezember 2014

Quick C Tricks - Simulate Keyword Arguments

Here is a little trick I found in the book Patterns in C written by Adam Tornhill. It will give you a syntax which looks like there are keyword arguments in C - but in fact there aren't:
int a, b, result;
result = sum(a = 2, b = 3);
This trick just moves the assignment of a and b insight the functions parameter section. However, this code is identical to:
int a = 2, b = 3, result;
result = sum(a,b);
So it is just some eye candy but are there any useful applications for that? Well, yes. This technique helped me to write some easy to read unit test code where I wanted to be explicit what the arguments of the function under test stand for.

Beside my unit tests I believe I won't use this syntactic sugar that often. If there is the need to pass in a couple of arguments to a function I would use this technique which relies on compound literals and designated initializers.

Keine Kommentare:

Kommentar veröffentlichen