Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double parentheses of a function call?

Tags:

c

syntax

gcc

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'

like image 679
vv1133 Avatar asked Apr 16 '12 13:04

vv1133


2 Answers

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 image 151
Some programmer dude Avatar answered Sep 28 '22 07:09

Some programmer dude


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.

like image 31
huon Avatar answered Sep 28 '22 09:09

huon