Evaluation order of operands

Consider the below program.

C

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int x = 0;
  
int f1()
{
  x = 5;
  return x;
}
  
int f2()
{
  x = 10;
  return x;
}
  
int main()
{
  int p = f1() + f2();
  printf("%d ", x);
  getchar();
  return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

class GFG 
{
  
    static int x = 0;
  
    static int f1() 
    {
        x = 5;
        return x;
    }
  
    static int f2() 
    {
        x = 10;
        return x;
    }
  
    public static void main(String[] args) 
    {
        int p = f1() + f2();
        System.out.printf("%d ", x);
    }
  
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach 
using System;
      
class GFG 
{
  
    static int x = 0;
  
    static int f1() 
    {
        x = 5;
        return x;
    }
  
    static int f2() 
    {
        x = 10;
        return x;
    }
  
    // Driver code
    public static void Main(String[] args) 
    {
        int p = f1() + f2();
        Console.WriteLine("{0} ", x);
    }
}
  
// This code has been contributed
// by 29AjayKumar

chevron_right



Output:

10

What would the output of the above program – ‘5’ or ’10’?
The output is undefined as the order of evaluation of f1() + f2() is not mandated by standard. The compiler is free to first call either f1() or f2(). Only when equal level precedence operators appear in an expression, the associativity comes into picture. For example, f1() + f2() + f3() will be considered as (f1() + f2()) + f3(). But among first pair, which function (the operand) evaluated first is not defined by the standard.

Thanks to Venki for suggesting the solution.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : Rajput-Ji, 29AjayKumar



Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.