Consider the following code:
#include <stdio.h>
int aaa(char *f, ...)
{
putchar(*f);
return 0;
}
int main(void)
{
aaa("abc");
aaa("%dabc", 3);
aaa(("abc"));
aaa(("%dabc", 3));
return 0;
}
I was wondering why the following lines:
aaa("abc");
aaa("%dabc", 3);
aaa(("abc"));
run without error, but the fourth line (seen below):
aaa(("%dabc", 3));
generates the following errors:
main.c:15:2: warning: passing argument 1 of 'aaa' makes pointer from integer without a cast
main.c:3:5: note: expected 'char *' but argument is of type `int'
The statement
aaa(("%dabc", 3));
calls the function aaa
with the argument ("%dabc", 3)
which returns the value 3
.
Look up the comma operator for more information.
Like in maths, the parentheses inside the function call are interpreted as grouping: e.g. (1) * (2)
is the same as 1 * 2
, but (1 + 2) * 3
is not the same as 1 + 2 * 3
.
In the first example aaa(("abc"))
: the inside parentheses are evaluated first, but ("abc")
is the same as "abc"
, so this is equivalent to just calling aaa("abc");
.
In the second example aaa(("abc",3))
: the inside expression is ("abc", 3)
i.e. the comma operator comes into play and "abc"
is discarded, leaving 3
as the argument to aaa
. The compiler is complaining because 3
has type int
not char*
so you aren't calling the function correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With