916 views
6 votes
6 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

2 Answers

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

3 votes
3 votes
2 answers
2
8 votes
8 votes
2 answers
3
1 votes
1 votes
3 answers
4