Reputation: 63
I have this method
foo_l(int *array, size_t l)
{
/*
code
*/
}
and I wrote this macro
#define foo(X) foo_l(X,sizeof(X)/sizeof(int))
So I can use them as follows
int main()
{
int a[]={1,2,3};
foo(a);
return 0;
}
and avoid writing the length of the array every time.
My question is, can I extend my macro so it can handle something like
foo_l((int[]){1,2,3}, 3);
with an array declared in the function parameter field?
Because foo((int[]){1,2,3})
doesn't work! I think that the problem is that the macro see (int[]){1,2,3}
as a list of parameters and not as a unique parameter. Any Idea?
P.S. I'm pretty new to the macro world and I usually use c99.
Upvotes: 0
Views: 3384
Reputation: 14751
When being passed to the preprocessor, the macro foo((int[]){1,2,3})
fails because the preprocessor believes it provided 3 parameters instead of 1:
foo((int[]){1,2,3});
// is believed to be:
// Start of macro: foo(
// Parameter 1: (int[]){1,
// Parameter 2: 2,
// Parameter 3: 3}
// End of macro: );
So it doesn't compile and gives something like:
a.c: In function ‘main’:
a.c:15:23: error: macro "foo" passed 3 arguments, but takes just 1
foo((int[]){1,2,3});
Adding another pair of parenthesis solves the problem:
// This shall work
foo(((int[]){1,2,3}));
Yes I guess this may not be a good design, since people like average programmers may be very likely to pass a pointer instead of an array type to your macro foo
, and it would fail as @DwayneTowell points out.
Please be careful about this.
:)
Upvotes: 3
Reputation: 8583
What you have suggested is not a good idea, because it will fail in cases like the following:
int a[] = {1,2,3,4};
int *b = a;
foo(b); // becomes foo_l(b,sizeof(b)/(sizeof(int));
// probably becomes foo_l(b,1)
In general the size parameter will be wrong if the first parameter is a pointer to an array instead of the array itself. Usually the expression will evaluate to 1, when sizeof(int *)==sizeof(int), which is very common but required by the standard.
Upvotes: 0