5
#include <stack>
using namespace std;

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
        printf("%d", s.pop());
    }
}

Whats wrong with the code above?

Error:

In function int main(): aggregate value used where an integer was expected

3 Answers 3

21

stack::pop is a void function which just discards the top element on the stack, in order to get the value you want to use stack::top.

The reason this is so is for exception safety reasons (what happens if the object returned throws an exception in its copy constructor?).

5
  • 3
    Ooh, never realized that was the reason. I always just thought it was a cleanliness of design/separation of concerns kind of thing. +1 for enlightening me. :)
    – jalf
    Apr 11, 2010 at 12:44
  • 2
    Also, pop would have to create a copy in order to return it. If the user doesn't want that, it's probably going to end up costing performance. Apr 11, 2010 at 14:39
  • 3
    According to Stroustrup (TC++PL), the actual reason was performance: if pop returned the value, it would have to create an unnecessary copy (since the value is consecutively destroyed in the stack). Both sound plausible though (and both are made obsolete by move semantics). Apr 11, 2010 at 20:41
  • 1
    @Konrad, since move contructor's are allowed to throw I don't think you can have an exception safe pop that returns the value. Not to mention the question of thread safety.
    – Motti
    Apr 12, 2010 at 6:16
  • But what about (N)RVO? Wouldn't pop just construct the top value directly, before "popping" it, so in case the exception happens - nothing will be lost. So no move constructors will be invoked anyway.
    – Dan M.
    Apr 13, 2018 at 1:10
2

Minor nitpick, your for loop is actually encoding 11 items and not 10 like you make think from a brief look at the loop count. Consider using < 11 if you mean 11 elements to add.

1

You're treating pop() which is an operation to print to standard output. pop() just removes the topmost element from the stack. The most confusing thing however is your debug output.

I compiled your code fragment with the standard GNU C++ compiler which gave me:

main.cpp|12|error: invalid use of void expression

int main() {
    stack<int> s;
    int i;
    for (i = 0; i <= 10; i++) {
        s.push(i);
    }
    for (i = 0; i <= 10; i++) {
          printf("%i", s.top());
          s.pop();
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.