Remove warning: "variable 'result' is used uninitialized whenever 'if' condition is false" in c++

Viewed 2223

I have seen questions similar to this one but none of them helped me due to the fact that I could not find one that was using a template. For a homework assignment, I have to code a stack that can be used with any type of variable, so I have decided to use a template. This prevents me from initializing variables, my code gives me a warning for the function pop() can anyone give me suggestions on how to remove such warning?

my function pop():

template<typename T>
    T stack<T>::pop(){
        T result;
        if(!empty()){
            result = tos->data;
            Node<T> *tmp = tos;
            tos = tos->next;
            delete tmp;
        }else{
            std::cerr<<"ERROR empty stack"<<std::endl;
        }
        return result;
    }
1 Answers

Instead of simply printing to std::cerr your pop() method should throw an exception if it hits something it cannot deal with. Silently failing and returning an uninitialized object will cause problems later.

You can throw an exception like this:

//...
else {
    throw std::runtime_error("ERROR empty stack");
}
//...

You then only need to declare result within the true branch of your if statement.

Related