546 views
void foo(int x)
{
int *p = &x;
*p = x*x;
}

The above code is supposed to modify any input integer with its square. Which of the following statements regarding the above code is correct?

1. The given code is wrong as C uses call by value and hence modification in function is lost during return
2. The given code is correct provided there is no overflow
3. The given code is wrong as it is not returning any value
4. The given code is wrong as it is illegal to access the memory of a parameter variable inside a function

void foo(int x)
{
int *p = &x;
*p = x*x;
}

Fucntion is called by Value i.e. foo(int x).

"The given code is wrong as C uses call by value and hence modification in function is lost during return"
​​​​

What asked in the question is "The above code is supposed to modify any input integer with its square."
So, the function itself should modify the input variable.

It isn't illegal to access the address of a local variable, however, it is illegal to return the address of a local variable (because its Activation Record would soon be popped off)

I'm assuming that's what Option D means? If it does, then we can eliminate Option D.

Option A is the most appropriate, as foo() accepts an integer variable as an argument (and not an address) which would mean it is pass by value, and hence the actual input whose square we want to obtain would stay intact.

Option A

1
2
749 views
3
922 views