226k views
5 votes
Functional side effects: 15) Given the following Java/C++ like code. Assuming function calls (operands) are evaluated from left-to-right, one at a time. a) What outputs are printed to the screen? int a = 4; // global variable int fun1() { a = 2; return 3; } int fun2() { return a; } void main() { int x = fun1() + fun2(); System.out.println("x = " + x); } Answer: x = b) What outputs are printed to the screen? int a = 4; // global variable int fun1() { a = 2; return 3; } int fun2() { return a; } void main() { int x = fun2() + fun1(); System.out.println("x = " + x); } Answer: x =

User Ylitc
by
6.0k points

1 Answer

6 votes

Answer:

a. x = 5

b. x = 7

Step-by-step explanation:

a)

OUTPUT: x = 5

In the main() function, fun1() is evaluated first and it updates the value of the global variable to 2 and returns 3.

The second function returns the value of the global variable 'a' and this variable has value 2.

So,

x = 3 + 2

x = 5

b)

OUTPUT: x = 7

In the main() function, fun2() is evaluated first and it returns 4 because global variable 'a' is initialized with value 4.

The second function fun()1 will returns the value 3.

So,

x = 4 + 3

x = 7

User Parth Kharecha
by
6.1k points