2

I have written a C program where I declared a function reverse(int i). When I compile and run the program, it runs fine despite passing two arguments like this reverse((i++, i)). Why doesn't this cause a syntax error? reverse expects one argument.

  #include <stdio.h>
    void reverse(int i);
    int main()
    { 
            reverse(1); 

    }
    void reverse(int i)
    {
            if (i > 5)
                    return ;
            printf("%d ", i); 
            return reverse((i++, i));
    }
Carcigenicate
  • 39,675
  • 9
  • 62
  • 99
  • 10
    `(i++, i)`is **one** parameter. – pmg May 06 '19 at 18:53
  • 2
    Passing `n` arguments to a function that accepts `k != n` arguments is not a syntax error, it's more of a type error (that is, semantics error). – ForceBru May 06 '19 at 19:03
  • 1
    If an answer solved your question, you can mark it as an answer by pressing the gray tick to the left of the question. – alx May 06 '19 at 19:26

2 Answers2

8

You're not passing two arguments - that would be reverse(i++, i) (which incidentally would invoke undefined behaviour because of the lack of a sequence point between (i++ and i).

You're passing (i++, i) as a single argument. Since it is inside an additional pair of parentheses, the comma here does not separate the arguments of the function, but rather acts as the comma operator.

sepp2k
  • 353,842
  • 52
  • 662
  • 667
5

(i++, i) seems to execute i++, then evaluate to i, the last operand to ,. You can see that here:

// Notice the ( , )
int i = (puts("Inside\n"), 2); // Prints "Inside"

printf("%d\n", i); // Prints 2

It didn't cause an error because you only passed one argument. That one argument though was a sequence of effects that evaluated to i.

Carcigenicate
  • 39,675
  • 9
  • 62
  • 99