Search code examples
cfunctionreturnargumentspass-by-value

C programming, manipulating functions' arguments and return


All

Should not the output be -24 ? I'm getting -4 as a result and can not get the reason .

   #include <stdio.h>
   int g (int x, int y) {
   x = x + y;
   int z = 2 * x - y;
   return z;
   }


int main()
{
    printf("Hello World%d\n", g(3, -10));

return 0;
 }

Solution

  • You call the function as

    g(3, -10)
    

    That means inside the function, the variable x starts out with the value 3 and y with the value -10.

    Now if we do the arithmetic on "paper" we first have

    x = x + y;
    

    which is the same as

    x = 3 + -10;
    

    which is the same as

    x = -7;
    

    Then you have

    int z = 2 * x - y;
    

    which is the same as

    int z = 2 * -7 - -10;
    

    which is the same as

    int z = -14 + 10;
    

    which is the same as

    int z = -4;
    

    And then you return the value of z which has the value -4.

    It's all elementary basic math as taught in most elementary schools.