/*
 * default-param.h
 *
 *  Created on: 24 Aug 2020
 *      Author: Nick Pelling
 */

#ifndef DEFAULT_PARAM_H_
#define DEFAULT_PARAM_H_

// Return the nth parameter
#define GET_ARG1(A,...)			A
#define GET_ARG2(A,B,...)		B
#define GET_ARG3(A,B,C,...)		C
#define GET_ARG4(A,B,C,D,...)	D
#define GET_ARG5(A,B,C,D,E,...)	E

// Join a function and its argument list together
#define FUNC_ARGLIST_JOIN(FUNC,ARGLIST)		FUNC ARGLIST

// Preprocessor "comma trick" macro: if this gets invoked, it evaluates to a comma
#define _TRIGGER_COMMA_(...)	,

#define IFEMPTY(...)

// If invoked with no (or an empty) second parameter, use the DEFAULT first parameter instead
// -- DEFAULT_PARAMETER(123)     evaluates to 123
// -- DEFAULT_PARAMETER(123,)    evaluates to 123
// -- DEFAULT_PARAMETER(123,456) evaluates to 456

#define _DEFAULT_PARAMETER2(DEFAULT,OPTIONAL)	\
	FUNC_ARGLIST_JOIN(GET_ARG5,(_TRIGGER_COMMA_ OPTIONAL (~) _TRIGGER_COMMA_ OPTIONAL, DEFAULT, OPTIONAL, DEFAULT, OPTIONAL))

#define DEFAULT_PARAMETER(DEFAULT,...)	_DEFAULT_PARAMETER2(DEFAULT,GET_ARG1(__VA_ARGS__))

#if 0	// Enable this to visually debug macro expansion test cases inside Eclipse
int default1 = DEFAULT_PARAMETER(123);
int default2 = DEFAULT_PARAMETER(123,);
int default3 = DEFAULT_PARAMETER(123,456);
int default4 = DEFAULT_PARAMETER(123,(456));
#endif

#endif /* DEFAULT_PARAM_H_ */
