I am currently developing a function
in C
to find the last char
occurrence of a given string. I want it to use a certain method (my own) if the length of the string is not given, otherwise it will just use strrchr
. So after a bit of researching I decided that a macro
would be the way to go. This is what I have:
size_t strlchr(const char *str, const char ch, const int strln)
{
//function code if strlen == -1 (no parameter)
//function code if strlen != -1 (parameter given)
}
#define strlchr_arg2(str, ch) strlchr(str, ch, -1)
#define strlchr_arg3(str, ch, strlen) strlchr(str, ch, strln)
#define getarg4(arg2, arg3, arg4...) arg4
#define strlchr_macro(...) \ getarg4(__VA_ARGS__, strlchr(arg3, \ arg2, )
#define strlchr(...) strlchr_macro(__VA_ARGS__)(__VA_ARGS__)
Is this the correct way of acheiving my goal? Or are there any more efficent ways? Also do I have to have the function code before the macro in the source file? I normally write my functions at the bottom, and have my declarations, in this case size_t strlchr(const char*, const char, const int)
towards the top of my source file, and finally my macros and such at the top of my source file. So ideally my layout would be:
macros/defines
function declaration
function code
This question is based completely off of other examples I saw from the web. Is this how one would go about using optional function parameters? Or am I way off? I haven't implemented it yet since I would first like to get some input before doing something horribly wrong (I have never made a macro before and this macro is for the most part taken from an example and I have minimal understanding of what it exactly does).