Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 882
Ashish Kumar Avatar asked Sep 14 '19 20:09

Ashish Kumar


People also ask

Why function should return a value?

If a function is defined as having a return type of void , it should not return a value. In C++, a function which is defined as having a return type of void , or is a constructor or destructor, must not return a value. If a function is defined as having a return type other than void , it should return a value.

What value is returned from a function that does not have a return statement?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

What type of value can a function return in JavaScript?

JavaScript functions can return a single value. To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object.

How do you return a value in JavaScript?

JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned.


1 Answers

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

x = x + 2; // x == 7 return x + 1; // returns 8 
like image 74
Nathan Xabedi Avatar answered Oct 21 '22 08:10

Nathan Xabedi