Universal macro which can have zero or one parameter [duplicate] - c

This question already has answers here:
How to define macro function which support no input parameter and support also input parametr in the same time
(4 answers)
Overload C macros
(2 answers)
Closed 8 years ago.
Is there any way to define macro which can have one or zero parameters?
I need something to be used as in this example:
#define MY_RETURN(ret) return ret;
void foo(){
MY_RETURN();
}
int foo_integer(){
MY_RETURN(1);
}
I am not able to find solution for this.

In C99 and later, it is possible to use variadic macros.
C11 (n1570), § 6.10 Preprocessing directives
# define identifier lparen identifier-list , ... ) replacement-list new-line
Your macro may look something like:
#define MY_RETURN(...) return __VA_ARGS__
If you need to count arguments, you may check here for instance.

Define two MY_RETURN macros, one with parameter and one without! A kind of overloading, but for macros.

Based on the answer of How to define macro function which support no input parameter and support also input parametr in the same time
Consider something like this:
#define MY_RETURN(ret) { \
int args[] = {ret}; \
if(sizeof(args) > 0) \
return ret; \
}

Related

Stringinize and concat macro parameters correctly [duplicate]

This question already has answers here:
Treating __func__ as a string literal instead of a predefined identifier
(4 answers)
Closed 4 years ago.
Basically, i have the following macro definition :
#include <stdio.h>
#define altErrMsg(x,y,z) x":"#y":"z
#define errMSG(x,y,z) altErrMsg(x,y,z)
#define __failure() errMSG(__FILE__,__LINE__,__FUNCTION__)
int
main (int argc, char **argv)
{
puts (__failure ());
return 0;
}
The macro __failure() is supposed to print some debugging information in the form "filename:line:function". For this purpose i used the GCC's predefined macros __LINE__, __FILE__ and __FUNCTION__. I used an indirection so that the predefined macros will be expanded before they are concatenated. The expansion of __LINE__ must be stringized (using the # before the parameter's name).
AFAIK, __failure() will be expanded to somthing like : "test.c"":""20"":""main" which will be quoted into a one single string constant "test.c:20:main". But that's not happening, instead, I'm getting errors :
test.c:5:46: error: expected ‘)’ before ‘__FUNCTION__’
#define __failure() errMSG(__FILE__,__LINE__,__FUNCTION__)
^
test.c:3:35: note: in definition of macro ‘altErrMsg’
#define altErrMsg(x,y,z) x":"#y":"z
^
test.c:5:21: note: in expansion of macro ‘errMSG’
#define __failure() errMSG(__FILE__,__LINE__,__FUNCTION__)
^~~~~~
test.c:10:11: note: in expansion of macro ‘__failure’
puts (__failure ());
Compiling with gcc -E shows that the __FUNCTION__ is never expanded and the final string looks like this : "test.c"":""22"":"__FUNCTION__ which is a wrong syntax but i have no idea why this happens !
Is there an explanation for this behavior ? and any correction to the issue ?
If you ask why then from Predefined macros
C99 introduced __func__, and GCC has provided __FUNCTION__ for a long time. Both of these are strings containing the name of the current function (there are slight semantic differences; see the GCC manual). Neither of them is a macro; the preprocessor does not know the name of the current function.
Not a macro - that's why not macro expanded. If this was your intention it won't work. (As you have seen).
Solution is to use a function where you will pass these things and print them accordingly. That would work.
void my_log( const char * filename, int linenumber, const char * funcname){
fprintf(sdtout,"%s[%d]%s\n",filename, linenumber, funcname);
}
And call like my_log(__FILE__,__LINE__,__FUNCTION__);.

How to detect a type is pointer in preprocessor of C? [duplicate]

This question already has answers here:
Check if a macro argument is a pointer or not
(6 answers)
Closed 5 years ago.
Is there a way to detect whether a type is pointer in preprocessor of C?
Suppose its name is IS_POINTER. What the final result I want may looks like:
#define DATA_STRUCTURE(KEY_T)
#if IS_POINTER(KEY_T)
/* do something */
#endif
Thanks!
The preprocessor has no notion of types, you cannot write such a macro that can be used in a #if directive.
Conversely, you can use some non-portable built-in functions to write an expression that does check if a given object is a pointer or something else.
Here is a macro to perform a static assertion that a is an array:
#define assert_array(a) \
(sizeof(char[1 - 2 * __builtin_types_compatible_p(typeof(a), typeof(&(a)[0]))]) - 1)
It can be used with gcc and clang. I use it to make the countof() macro safer:
#define countof(a) ((ssize_t)(sizeof(a) / sizeof(*(a)) + assert_array(a)))
You could try using typeof(expr), which may help you in your task. It doesn't exactly tell you something is a pointer, but perhaps you could use it in comparisons:
https://gcc.gnu.org/onlinedocs/gcc/Typeof.html

Do function like macros need a mandatory parentheses? I am confused after referring the GCC cpp manual

Here is what confuses me:
To define a function-like macro, you use the same '#define' directive, but you put a pair of parentheses immediately after the macro name.
I believe this is to make the code stand out for people other than the author of the program. Like other rules of CAPS for macro names. But the following is where I get confused:
A function-like macro is only expanded if its name appears with a pair of parentheses after it. If you write just the name, it is left alone.
I disagreed instantly after reading it. And gcc -E verified that in the following code
#define FUNC display()
void display()
{
printf("Display\n");
}
int main()
{
FUNC;
return 0;
}
The pre-processed output shows the content of the main() function as expected:
int main()
{
display();
return 0;
}
So what am I missing here? The pre-processor is for tokenizing the source, the macro expansion is a token and the above code was processed that way, the pre-processor isn't supposed to check anything or verify anything, it just dumps tokens. In that case what is the gcc manual trying to convey.
I am learning C programming, so I might be misunderstanding it a great deal as it frequently happens, I searched for a proper explanation and finally resorted to asking here. Please help me with this.
When you define:
#define FUNC display()
FUNC is not a function-like macro; it is an object-like macro that expands to a function call.
A function-like macro looks like:
#define FUNC() display()
Now you must write FUNC() to invoke it. Or, more frequently, it will have arguments:
#define MIN(x, y) ((x) > (y) ? (x) : (y))
and that can be invoked with:
int min = MIN(sin(p), cos(q));
with cautions about the number of times the arguments are expanded.
See also getc() as macro and C standard library function definition. It includes the standard's explanation of why it is important that the simple name of a function-like macro without a following open parenthesis is not expanded, which is what the quote from the GCC manual is telling you.
When a function-like macro is defined, the open parenthesis must 'touch' the macro name:
#define function_like(a) …
#define object_like (…)
Because there's a space after object_like, the open parenthesis is part of the replacement text, not the start of an argument list. When the function-like macro is invoked, there may be spaces between the macro name and the argument list:
function_like (x) // Valid invocation of function_like macro.
However, if you wrote:
int (function_like)(double a) { return asin(a) + 2 * atanh(a); }
this is not an invocation of the function-like macro because the token after function_like is not an open parenthesis.
There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.
You may define any valid identifier as a macro, even if it is a C keyword. The preprocessor does not know anything about keywords. This can be useful if you wish to hide a keyword such as const from an older compiler that does not understand it. However, the preprocessor operator can never be defined as a macro, and C++'s named operators cannot be macros when you are compiling C++.

I am unable to understand the execution of following c code [duplicate]

This question already has answers here:
Macro expansion in context of arithmetic expression?
(6 answers)
Closed 7 years ago.
#include <stdio.h>
#define sqr(a) a*a
int main()
{
int i;
printf("%d",64/sqr(4));
return 0;
}
Why am I getting the output as 64 .
Normally what should happen is it first checks the value for sqr(4) and then divide . In case of any other operator it works fine .
Please Explain .
After preprocessing the printf line will be:
printf("%d",64/4*4);
which should explain why it prints 64.
Always use parenthesis in macros definitions when they contain expressions:
#define sqr(a) ((a)*(a))
Even this is not safe against macro invocations like: sqr(x++). So don't use marcos unless you have to :)
Macros aren't functions, they're (mostly) dumb text replacement. Your macro lacks parentheses, so when the preprocesor replaces it, you'd get the following:
printf("%d",64/4*4);
Since / and * have the same precedence, this is like stating (64/4)*4, which is, of course, 64.
If you want your sqr macro to safely square its argument, wrap it in parentheses:
#define sqr(a) (a*a)
64/sqr(4) is expanded to 64/4*4.
You have to parenthetise the macro body and should also put parenthesis aroud the argument:
#define sqr(a) ((a)*(a))
Yields:64/(4*4)
Note that macros are pure textual replacements performed by the C preprocessor before the actual compilation starts.
A better and type-safe approach would be to use an inline function:
static inline int sqr(int a)
{
return a * a;
}
This will likely be inlined into the caller code by the compiler as much as the macro would be. OTOH, the compiler might very well decide not to, depending on internal heuristics. In general, you should trust the compiler to use the proper way, unless you have serious performance/code-size issues.
This will also protect against evaluating the argument a twice. That is critical if there are side-effects like
int i[2], *p = i;
sqr(*p++);
For the macro version, this will result in undefined behaviour (undefined order of evaluation):
((*p++) * (*p++))

C to use defined macro in current macro block [duplicate]

This question already has answers here:
How can I concatenate twice with the C preprocessor and expand a macro as in "arg ## _ ## MACRO"?
(3 answers)
Stringification - how does it work?
(2 answers)
Closed 7 years ago.
I am implementing a generic Hash Table in C using macros.
As one example, I defined key, value types as
#define h_key_type int
#define h_val_type int
Then I defined put function as:
#define H_PUT(key_type, val_type) \
void key_type##_put(...)
H_PUT(h_key_type, h_val_type);
However, after preprocessing the processed source codes become
void h_key_type_put(...)
Even I changed the function declaration as:
#define H_PUT() \
void h_key_type##_put(...)
it's still replaced as:
void h_key_type_put(...)
So I have to use
#define H_PUT(key_type, val_type) \
void key_type##_put(...)
H_PUT(int, int)
to make it work.
But it's not convenient since I either have to introduce a gigantic define block, or I have to type key, value types for each function, which is not elegant.
Any ideas?

Resources