void (assert)(int e)
{
assert(e);
}
How does it work here?
void (assert)(int e) is equivalent to void assert(int)
Why would you need it?
Consider the following example
#include<stdio.h>
void foo(int a)
{
printf("%d", a);
}
#define foo(a) {/*I do nothing*/}
int main()
{
foo(5); // won't call `foo`
}
How would you make sure when you call foo, its the function that is called and not the macro-definition substituted at the place of call?
The solution is to put an extra parenthesis like (foo)(5)
Similarly assert is already known to be a macro. That's the reason I can think of.
Since assert already is defined as a function-style macro, without the parentheses it would have been expanded both in the function header and in the body.
For example:
#define twice(x) ((x)+(x))
void twice(int i)
{
return twice(i);
}
Will expand to the following, which clearly is not legal
void ((int i)+(int i))
{
return ((i)+(i));
}
On the other hand:
#define twice(x) ((x)+(x))
void (twice)(int i)
{
return twice(i);
}
Will expand to:
void (twice)(int i)
{
return ((i)+(i));
}
The extra parentheses around the function name is simply ignored by the compiler.
This is a common trick often used in the source of the standard library, on in other contexts where there might be functions and macros with the same name.
It's legal syntax, just writing it with extra parentheses. The reason you'd do that is because assert() is often defined as a macro; so the above function exists to make assert() be a real function, probably so you can set a breakpoint in it.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
I am checking the input arguments provided and if it is not in the range specified, it should exit from the function. Suppose I have called a function, Func(arg). If arg is not in the specified range, the function should return to main().
The code sample is as follows:
#define check_param(expr) ((expr) ? (void)0U : exit(3))
void Func(int arg)
{
check_param(arg);
...
...
}
int main()
{
...
Func(10);
...
return 0;
}
If I use exit(), it will exit the whole program. I want to return to main() and execute further instructions. I can't use return as it is a statement. What can be used in place of exit(3)?
The above definition is used for both type of functions (void and int type).
Do not hide the return, that's just asking for trouble. Simply replace this part:
#define check_param(expr) ((expr) ? (void)0U : exit(3))
void Func(int arg)
{
check_param(arg);
with this:
// suggestion: return 0 on success, or error code
int Func(int arg)
{
if (!arg) return 3; // error code
...
return 0; // no error
}
Using funny macros does not make the code easier to read, and they can be a real head-ache when debugging.
You do not need to use only an expression as the replacement sequence for a macro. It can be a statement (or part of one), such as:
#define check_param(expr) if (!(expr)) return
Since you want the macro to work in functions that return void and in other functions, we need to give it a way to have a matching return statement, one that either does or does not give a return value, as desired. We can do this with another parameter:
#define check_param(expr, value) if (!(expr)) return value
Then the macro can be used:
check_param(arg,); // In function that returns void, value is blank.
check_param(arg, -1); // In other functions, value is not blank.
Note that in return value, value is not in parentheses. It is usual to enclose macro arguments in parentheses to avoid precedence issues, but that cannot work here because we need return value to work when value is blank, and return (); would cause a syntax error.
Finally, when defining a macro as a statement, there is an idiom to wrap it in a do-while statement so that it acts grammatically like an ordinary statement:
#define check_param(expr, value) do if (!(expr)) return value; while (0)
Note that, in the original if form, if the macro invocation happens to be followed by an else, like this:
if (A)
check_param(arg, value);
else
MyRoutine(arg);
then the else would be associated with the if resulting from the check_param macro instead of with the if (A). By wrapping the macro in do … while, we prevent this sort of undesired interpretation.
I do not see any use of such a macro (maybe to make the code more difficult to read)
I would use statements, not expressions.
This Macro will work both for void (second macro parameter blank after comma) and non void functions. cond and retval can be expressions objects or constants. retval does not have to be in parentheses as it is normally in macros because there are no other operations in this statement.
#define check(cond, retval) do{if(!(cond)) return retval;}while(0)
int foo(int x)
{
check(x == 2, x * 2);
/* ... */
return something;
}
void bar(const char *s1, const char *s2)
{
check(!strcmp(s1,s2), );
}
https://godbolt.org/z/hY9rKe4xs
Example more real usage:
int div(const int x, const y)
{
check(y != 0, INT_MIN);
return x / y;
}
Is there a way to build a wrapper function in C as follows:
void wrapper(void *func) {
// Set up
func([same arguments as func was passed in with]);
// Clean up
}
void foo(int x, int y);
void bar(char *z);
wrapper(foo(1, 2));
wrapper(bar("Hello"));
It seems as though you have to either pass in the arugments within wrapper or only support one type of method header for func. I've been writing a lot of Javascript... and of course this is possible in JS.
That's the best I can think of with variadic function wwrappers:
#include <stdio.h>
#include <stdarg.h>
void wrapper(void (*func)(va_list), ...) {
va_list args;
va_start(args, func);
func(args);
va_end(args);
}
void foo(int x, int y)
{
printf("foo(%d,%d)\n", x, y);
}
void vfoo(va_list args)
{
foo(va_arg(args, int), va_arg(args, int));
}
void bar(char *z)
{
printf("bar(%s)\n", z);
}
void vbar(va_list args)
{
bar(va_arg(args, char*));
}
int main()
{
wrapper(vfoo, 1, 2);
wrapper(vbar, "Hello, World!");
return 0;
}
Live example on Coliru.
Have you considered (ab)using the preprocessor?
#include <stdio.h>
#define wrapper(f) /* Set up */\
f; \
/* Clean up */
void foo(int x, int y) {
printf("x: %d; y: %d\n", x, y);
}
void bar(char *str) {
printf("str: %s\n", str);
}
int main(void) {
wrapper(foo(42, 11));
wrapper(bar("hello world"));
}
To elaborate upon why I added the possibility of an ab- prefix to (ab)use, I wouldn't hesitate to use whatever is the most expressive solution to a problem, regardless of the attitude held by the general populus. However, I recognise that sometimes we have no control over the restrictions we are bound by, and policies are often put in place to heavily restrict the use of macros. Unfortunately, those bound by such silly policies won't find this post too helpful.
In a comment above I suggested that "if you want a feature from Javascript you should probably write your code in Javascript...".
Upon pondering about this overnight, I came to the conclusion that features similar to those you ask are actually doable and would be quite nice in C... so I admit, I was wrong.
The following is an example of mimicking how Javascript treats functions.
#include <stdio.h>
struct argument;
typedef struct argument argument;
typedef void function(argument *);
struct argument {
function *function;
/* for foo() */
int x;
int y;
/* for bar() */
char *str;
};
void wrapper(argument *a) {
// set up
a->function(a);
// clean up
}
void foo(argument *a) {
printf("x: %d; y: %d\n", a->x, a->y);
}
void bar(argument *a) {
printf("str: %s\n", a->str);
}
#define foo(...) wrapper(&(argument){ .function = foo, __VA_ARGS__ })
#define bar(...) wrapper(&(argument){ .function = bar, .str = "", __VA_ARGS__ })
int main(void) {
foo(.x = 42, .y = 11);
bar(.str = "hello world");
}
There are actually some really nice features coming from this style of wrapper:
It becomes very difficult for a down-stream programmerr to mung the stack, where-as it is very easy for programmers using typical variadic functions such as printf and scanf to cause subtle yet devastating bugs by passing the wrong types and/or values to those functions. This leads on to my next point:
Default argument values are possible by simply modifying the foo and bar macros. As an example in the code above, the default value for the argument named str is set to "" (an empty string) for bar.
By introducing extra logic into wrapper, you can mimic partial function application (or binding properties to functions, much like you'd see in Javascript). Additionally, with a little bit of effort, mimicking continuation passing style might be possible by turning wrapper into a trampoline-style function and modifying the return value? I'll ponder more on this and provide an update tomorrow.
Finally, down-stream users are encouraged to pair argument identifiers with argument values, which improves maintainability drastically.
There are some minor draw-backs, the most significant being that neither foo nor bar can be passed, unapplied, to another function as an argument. This would be rare for these functions specifically, as they differ greatly in signature, but for functions that are identical or even similar in signature I can understand one might want to pass them as callbacks or what-not.
The solution to that problem is to rename the macros to default_foo and default_bar or something like that...
Finally, thanks for asking such a thought-provoking question... I hope reading my answer has been as interesting for you as thinking about (and writing) it was for me.
I'd like to declare the following function with multiple names:
static __inline__ int square(int i) {
return i * i;
}
It only has to work with GCC 4.x (for some useful value of x)
I've tried __asm__, but it works for non-static functions only, so this doesn't work:
static __inline__ int square2(int i) __asm__("square");
I've tried alias, but it prevents the call to square2 from being inlined, but I want inlining for both square and square2, equivalently.
static __inline__ int square2(int i) __attribute__((alias("square2")));
I've tried a macro, but that prevents me from using independent local variables named square and square2 in other unrelated functions. So I can't accept this:
#define square2 square
I know about writing another call, but I don't like it, because it's one more indirection for the optimizer, and it may prevent inlining in some complicated case:
static __inline__ int square2(int i) { return square(i); }
Is there another solution?
I guess your "real" code has a more complicated function than a single statement? Else the obvious choice is to repeat the definition with the second name.
You could make it a macro, of course:
#define SQUARE_BODY(a) return (a) * (a);
static inline square(int x)
{
SQUARE_BODY(x);
}
static inline square2(int x)
{
SQUARE_BODY(x);
}
Of course you can fold more of the function definitions into the macro, but I think that having it only be the body part makes the rest of the code clearer.
Can the name of function and function-like macro be same?
Wouldn't this cause any problem?
They could be the same. Depending on how you use the name, either it gets replaced by preprocessor or not. For example
//silly but just for demonstration.
int addfive(int n)
{
return n + 5;
}
#define addfive(n) ((n) + 5)
int main(void)
{
int a;
a = addfive(2); //macro
a = (addfive)(2); //function
}
for ex. MS says that: http://msdn.microsoft.com/en-us/library/aa272055(v=vs.60).aspx
http://gcc.gnu.org/onlinedocs/cpp/Function-like-Macros.html#Function-like-Macros
Here you can see that calling the function, of which a macro with the same name exists, calls the macro instead :)
For the gcc at least!
This would cause no problem, but quite some confusions. I wouldn't recommend this.
I will explain via cases:
If you declared the function first then the function like macro second, macro will over take the function. i.e. it will be called always instead of the function.
//Function
double squar(double x)
{
return x*x;
}
//Macro
#define squar(x) (x*x)
On the other hand if you declare the macro first then the function later, an exception will be arise, you wont be able to build
//Macro
#define squar(x) (x*x)
//Function
double squar(double x)
{
return x*x;
}
At the end, in the first case, you still call the function like #Hayri Uğur Koltuk said here in his answer by (squar)(5)
I've got a bunch of C functions which get assigned to an array of function pointers, along the lines of this:
typedef int (*func)(int);
int SomeLongName1(int a) {
// ...
}
// ...
int SomeLongName1000(int a) {
// ...
}
func f[] = { SomeLongName1, ... , SomeLongName1000 };
This is a lot of work to create and is prone to errors. For instance, there could be a typo in the function name such that a valid function is still named, but the wrong one. Or, if a new function is added at the end one could forget to go in and explicitly add it to the list of function pointers as well.
In order to avoid having to explicitly declare the array of function pointers I have tried various tricks such as macros, which make the code hard to understand and require knowing how the macro works, and I am generally unsatisfied with them.
What I would like to do is something like this:
typedef int (*func)(int);
func f[] = {
int SomeLongName1(int a) {
// ...
}
// ...
int SomeLongName1000(int a) {
// ...
}
};
This way, the array would be automatically created, and if there was some way to put a null pointer at the end so I can determine how many function pointers there are that would be great as well.
However, the above isn't valid C and I'm coming up empty with any way of accomplishing this. If it is something compiler specific (e.g. a GCC extension) that would be ok.
All the functions are statically known at compile time, so I would like to avoid having to do any run-time initialization of the function pointer array - not that I have found a method to do it that way either.
This related question How to define an array of functions, seems to ask the same question, but does not carry it to its logical conclusion. Specifically, I don't want to have to re-type anything I have already typed so as to save time and avoid errors.
If you don't care about the order of functions in the array, and are willing to use a GCC extension, then you can achieve what you want using a whole bunch of initializer (constructor) functions. This obviously isn't ideal because of the sheer number of extra functions defined, but it is certainly one approach you can consider. It constructs the array at runtime.
Define the function append to append a single function to an array (reallocating if needed). Then, the code is basically
#define ARRAYFUNC(name) int name(int); \
void __attribute__((constructor)) __init_##name(void) { append(func); } \
int name(int a)
ARRAYFUNC(func1) {
...
}
ARRAYFUNC(func2) {
...
}
You could use the C preprocessor (X-Macros) for this:
#include <stdio.h>
// define a list of function names and bodies
#define FUNCS \
FUNC(add, { return a+b; }) \
FUNC(mul, { return a*b; }) \
FUNC(div, { return a/b; })
// let the preprocessor make up the actual function implementations
#define FUNC(name, body) int name(int a, int b) body
FUNCS
#undef FUNC
typedef int (*func)(int, int);
// let the preprocessor populate the array of function pointers
func f[] = {
#define FUNC(name, body) name,
FUNCS
#undef FUNC
};
// use it:
int main () {
int a = 2, b = 3, i = 0;
for (; i < sizeof(f)/sizeof(*f); i++) {
printf("%d\n", f[i](a,b));
}
return 0;
}
The output is:
$ gcc test.c && ./a.out
5
6
0
What I would use to solve such a situation (only if I can't avoid it, of course), is to use preprocessing. Not the one available from the C preprocessor, it does not provide the required functionality in a sensible syntax, but a really powerful one like m4.
With m4, your code could look like this:
define(`functionList', `, 0')
define(`functionArrayMember', `define(`functionList', `$1, 'FunctionList)$1')
define(`buildFunctionArray', `{ functionList }')
int functionArrayMember(SomeLongName1)(int a) {
return a+1;
}
//...
int functionArrayMember(SomeLongName1000)(int a) {
return a+1;
}
func f[] = buildFunctionArray();
You just need to provide the right m4 definition for functionArrayMember() and buildFunctionArray(), and you have the functionality you need.
I do not think there is any other way of doing what want to do.
What you wrote
func f[] = { SomeLongName1, ... , SomeLongName1000 };
already does what is best.
Maybe you could name your functions with an prefix 0000 to 1000, so that you can be sure each function is in the right place in your functions pointer array.
Also, if you really have 1000 different functions, they are surely things in common that could lead you to sort them in several arrays, reducing the numbering effort, and that is less error prone.