Quote:Original post by J0Be
Hi guys,
Just wanted to ask about a part of the text in the book that goes like this:
Page. 130 Last paragraph states the following and I quoteQuote:
Last-in, first out means that whatever is added to the stack last is the first thing taken off. This differs from most queues in which the first in is the first out (like a line at the theater).
Shouldn't the queues be first in, last out?
Meaning:
Stack: First in, First out 'FiFo'
Queu: First in, Last out 'FiLo'?
Nope, the book has it right. Think of a stack of papers. Someone puts a new paper on the top of the stack and you grab the top most paper to work on it. The last page put on the stack is the first one you grab. Likewise, if someone puts one page on top of another the stack gets higher and higher. The first page put down can't be removed until all the pages above it are removed. Hence the 'first in last out'.
As for a queue, if you were standing in line for a drink of water and got there first, would you be the last person to get a drink? No! You'd be the first person to get a drink. If five people got in line, say first Alice, then Bob, Carrie, Dave, and finally Eliza, then Alice would leave first, then Bob, Carrie, Dave, and finally Eliza. Or ordering from a restaurant that can only cook one thing at a time. Or being put on hold for a help-line where it tells you 'there are 20 people ahead of you".
Quote:
Exercise:5_6
Using the call to a function as an expression? Is that often done or good coding habit?
The exact type of line
if ((result = Division(0, 1)) == -1) // <--- this part???
That is, the call to a function itself is pretty common, but assigning the result while at the same time comparing the result to something else is something I personally avoid. I would have written that code like this:
int result = Division(0,1);if(result == -1)
However, as I said, it IS pretty common to use a function as an expression. It depends on the function and it depends on the expression though. The problem with that particular example you gave is that the function returned either an error code (-1) or a result. This wouldn't be so bad if there wasn't valid input that would give -1 as a result (say Division(-2, 2); ). There are a number of different ways to write a function to take care of this kind of situation. If you use exceptions you can just throw an error, you can write the code under the assumption that no one will ever give 0 in the denominator(add an assert(denominator != 0); ). Maybe you can write something like this:
bool Division(double numerator, double denominator, double &result){ if (denominator == 0) { return false; } result = numerator / denominator; return true;}int main(){ int answer; if(Division(-2, 2, answer) ) { cout << "Answer: " << answer << endl; } else { cout << "Divide by zero error" << endl; }}
Hope that helps.