Search code examples
creturn-valuecomma-operator

Why is the return value of the fun function 8 instead of 7?


With reference to Comma-Separated return arguments in C function [duplicate] ,

x=x+2,x+1;

will be evaluated as

x=x+2; 

However, in case of the following code

#include<stdlib.h>
#include<stdio.h>

int fun(int x)
{
    return (x=x+2,x+1); //[A]
}

int main()
{
   int x=5;
   x=fun(x);
   printf("%d",x); // Output is 8
}

Shouldn't line [A],be evaluated as

x=x+2;

giving x = 7


Solution

  • The statement return (x = x + 2, x + 1); is equivalent to:

    x = x + 2; // x == 7
    return x + 1; // returns 8