Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions chapter_4/exercise_4_04/stack.c
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,10 @@ void swap(void)

void clear(void)
{
do
while (sp > 0)
{
stack[sp] = 0.0;
} while (sp--);
stack[--sp] = 0.0;
}
Comment on lines +161 to +164
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sadeem-albir Is this code required to change? What's the bug here? Is it that pre decrement that useful?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ohkimur If my assumption is correct, the sp works the same as buf and bufp. whenever you add something to the stack, you do stack[sp++], meaning the current index (zero) will be assigned then sp will be the next unassigned index. So by using that other while-loop instead, you ensure you move to the previous assigned sp until you reach zero. Also, in the do-loop, even if sp was zero, it will be decremented, undesirably becoming -1.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sadeem-albir With this approach, I think the first location from sp will be always empty. Can you verify that? What do you think would be better here? If the previous approach is better, I propose we go with that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ohkimur Not necessarily a negative impact. As you see in the pop function, you return stack[--sp] so sp is meant to be empty at whatever current index it is lying at for the moment, and when we need to use a value from the stack, we simply call the previous index of sp, so if the stack was [1, 2, 3, 0] and sp is 3, calling pop will return the value of 3 at index 2. The change I have proposed ensures consistency with the way sp changes in the other stack functions, but if you believe staying at the previous change is better for the program, then the change doesn't have to be merged.

}

int bufp = 0;
Expand Down Expand Up @@ -215,10 +215,6 @@ int getop(char s[])
s[++i] = c = next;
}
}
else
{
c = getch();
}

if (isdigit(c))
{
Expand Down