edited by
7,029 views
25 votes
25 votes

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 by

3 Answers

Best answer
24 votes
24 votes
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.
edited by
16 votes
16 votes

Option C.

Since the programming language in the syllabus for GATE is: C. So, I would try to write the closest program for the given construct.

Pass by Value:(which is more likely the case here)

#include<stdio.h>
int x, result;

int f(int x)
{
	x = x+1;
	return x;
}

int main()
{
		x = 5;
		result = f(x)*f(x);
		printf("final result : %d\n",result );

	return 0;
}

Output:


final result : 36

But I would also write the closest program to pass by reference, just for overall analysis.

Pass by reference:

#include <stdio.h>

int x =5;

int f(int *p)
{
	(*p)++;
	

	return *p;
}

int main(int argc, char const *argv[])
{
	int *ptr = &x;

	int out;

	out = f(ptr) * f(ptr);

	printf("output : %d\n",out );
	return 0;
}

Output:

output : 42

 

9 votes
9 votes

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

Answer:

Related questions

29 votes
29 votes
6 answers
1
Kathleen asked Sep 25, 2014
13,711 views
What value would the following function return for the input $x=95$?Function fun (x:integer):integer; Begin If x 100 then fun = x – 10 Else fun = fun(fun (x+11)) End;$...
28 votes
28 votes
1 answer
2
Kathleen asked Sep 25, 2014
8,681 views
Faster access to non-local variables is achieved using an array of pointers to activation records called a stackheapdisplayactivation tree
42 votes
42 votes
4 answers
3
Kathleen asked Sep 25, 2014
9,978 views
What happens when a bit-string is XORed with itself $n$-times as shown:$\left[B \oplus (B \oplus ( B \oplus (B \dots n \text{ times}\right]$complements when $n$ is evenco...
31 votes
31 votes
3 answers
4