2.5k views

What is the result of the following program?

    program side-effect (input, output);
var x, result: integer;
function f (var x:integer:integer;
begin
x:x+1;f:=x;
end
begin
x:=5;
result:=f(x)*f(x);
writeln(result);
end

1. $5$
2. $25$
3. $36$
4. $42$

edited | 2.5k views

Call by value: $36$,
Call by reference: undefined behaviour for C/C++ but $42$ for languages having $*$ as a sequence point.

$f(x) * f(x);$

If the value of $x$ is being modified inside the function (call by reference) we cannot be sure if this modified value or the old value will be passed as argument for the second call to $f()$. This is because left and right operand of any arithmetic expression in C/C++ can be evaluated in any order. For languages like Java, strict left-right order is maintained.
by
edited
+1
Arjun sir,

1. If we pass by value then ,x is a local variable in function f.So even if it increments global remains same.I am not getting how you are getting 36 for call by value?Also, what if f=x statement means?
+10
yes, global x remains same but the local x in f gets incremented. "f = x" means the function f is returning the value x.
+5
No need to worry about such notations-- it will be pretty clearly stated if asked now.
0
ok.Thanks for explanation sir.
0
Sir,one more thing if you can help. For the call by reference case,the undefined ouput will be from 36 or 42 or it can be anyhting?
+1
If it is call by reference then 49 will be ans
in case of call by value 36 will ans
0
how 49 srestha?
+1
If it is call by reference

x=7

then f is also 7

then result f(x)*f(x)=7*7=49

Same location pointed all time na?
0
and x is 5 here
+1
yes x=5

In time of 1st function call,

f also points to value 6

Now again function called

x becomes 7

f also points to memory location of x

Now multiplication happened

So, f(x) is pointing to same memory location of x i.e.7

Now, 7*7=49

is it ok now?
0
okay i got your explanation for 47 , now i have doubt about evaluation of f(x)*f(x)

why can't  first f(x) evaluates first and gives 6 and then second f(x) gives 7 , eventually 42?
0

I tried to run this program in pascal but it is showing fatal error.

how will call by reference work here?

0

,how it get 49??? ,1st f(x) will give 6 and second will give 7, so does it be 42?