Alicia Sabatino Alicia Sabatino - 27 days ago 9
C++ Question

Return statement breaking my function c++

So I call a function in main:


Which goes here

Then finally here:

int MyClass::remove() {
cout << "this is the remove function"<< endl; //debugging line

int lastVal = 0;

for (int i = start; i < capacity; i++) { //actual remove function
if (m_array[i] != NULL) {
int lastVal = m_array[i];
m_array[i] = NULL; // sets to null
m_size--; //increment
m_start++; //increment
return lastVal;

If I remove the code containing lastVal, the function works properly. Why is this? Is there an easy way to fix this?
As you can see I'm attempting to return a value before removing it from the array. I am aware I should be using vector or some other standard method, but I cannot. I looked in my textbook but I couldn't find what I was looking for. Any help is greatly appreciated.

Answer Source

You have two int lastVal statements in your code - one before the for loop and one in it. Try removing the declaration inside the for loop (and set it to the assignment lastVal = m_array[i];) and see if it works.