Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I was asked following question in an interview and was asked that it is having sanity check issues. Could anyone please help me in this:

//following function should increment the value of x
C++
void increment(int x)
{
    x++;
    return; 
}


Regards

What I have tried:

I have asked to change copy by value to pass by reference by it was still giving error.
Posted
Updated 28-Apr-19 20:22pm
Comments
Christian Graus 29-Apr-19 1:52am    
This code should not give an error. If you pass by reference, then x will be incremented in the calling code. If you changed it and got an error, give us the new code and the error if you're stuck

This code should not give an error. If you pass by reference, then x will be incremented in the calling code. If you changed it and got an error, give us the new code and the error if you're stuck
 
Share this answer
 
Comments
Rahul@puna 29-Apr-19 1:56am    
There was no specific error as such. I was doing this thing on a interview portal and their after checking with reference , it is compiling ok but giving some sanity error. that i am trying to figure out. what could be missing here.
Christian Graus 29-Apr-19 1:59am    
This will do nothing. It increments a local variable and returns. If you make it a ref, then it will pass by reference and increment the variable in the calling code

You could also pass in a pointer and get the same result. You'd have to dereference the pointer to increment it though.
Rahul@puna 29-Apr-19 2:01am    
Yes actually I have updated the code. Following is that that i have updated to but still it was giving sanity check error.

void increment(int& x)
{
x++;
return;
}
Christian Graus 29-Apr-19 2:02am    
What is a 'sanity check error'?
Rahul@puna 29-Apr-19 2:04am    
not sure of that, it's in their tool. May be they are doing some validation of the function and then giving output on the basis of that. I need to figure out what could be wrong with this function in any case.
One issue in this function can be that it has NO EXTERNAL EFFECTS. The input x is created on the stack, locally modified and than destroyed.

So the function only modies the local x and nothing more. You can change this behaviour with the &-operator, as mentioned before.
 
Share this answer
 
Comments
Christian Graus 29-Apr-19 2:24am    
That was the point here. he was given a function that did nothing and asked to make it work

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900