1.8k 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 | 1.8k 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 Veteran (420k points)
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?
+7
yes, global x remains same but the local x in f gets incremented. "f = x" means the function f is returning the value x.
+3
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?
0
If it is call by reference then 49 will be ans
in case of call by value 36 will ans
0
how 49 srestha?
0
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
0
yes x=5

In time of 1st function call,

then increment x+1, it becomes 6 and assign inside x

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?

Answer is (d) :

Why? Since in question syntax is like pascal we will assume that this segment follows rules of Pascal programming language. Then , there is rule in pascal that if in declaration of formal parameters keyword 'var' is prefixed , then the procedure follows call by reference and modifies the actual values of actual params. So  the answer is 42.

https://www.tutorialspoint.com/pascal/pascal_call_by_reference.htm

by (75 points)
0
Whatever you're saying is correct. can't comment about 98 but now GATE don't ask individual language base questions...they will explicitly mention about parameter passing.