in Programming
517 views
5 votes
5 votes
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
in Programming
by
517 views

2 Answers

4 votes
4 votes
Best answer
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"
​​​​

selected by

2 Comments

what's about option(c)
0
0
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.
0
0
0 votes
0 votes

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

Answer:

Related questions