Neste código:
// Stack using LinkedList //
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
short isEmpty(void) {
if (top == NULL) {
printf("error: The stack is empty.\n");
return 1;
}
return 0;
}
void push(int value) {
struct Node* newNode = (void*)malloc(sizeof(struct Node));
if (!newNode) {
printf("error: Heap overflow!\n");
exit(1);
}
newNode->data = value;
newNode->next = top;
top = newNode;
}
int pop(void) {
if (isEmpty()) {
exit(1);
}
struct Node* ref = top;
int val = top->data;
top = top->next;
free(ref);
return val;
}
int peek(void) {
if (isEmpty()) {
exit(1);
}
return top->data;
}
void display(void) {
if (isEmpty()) {
exit(1);
}
while (top) {
printf("%d\n", top->data);
top = top->next;
}
}
int main(void) {
push(10);
push(20);
push(30);
push(40);
printf("Peek: %d\n", peek());
int val = pop();
printf("Popped: %d, now Peek: %d\n", val, peek());
push(50);
display();
return 0;
}
Observe estas linhas:
int val = pop();
printf("Popped: %d, now Peek: %d\n", val, peek());
Ele retorna:Popped: 40, now Peek: 30
como esperado. No entanto, ao escrever desta forma:
printf("Popped: %d, now Peek: %d\n", pop(), peek());
Ele produz esta saída:Popped: 40, now Peek: 40
Aqui está um Godbolt .
Alguém pode me esclarecer por que é assim?
A ordem de avaliação dos argumentos da função não é especificada. Então, quando você faz isso:
Ou
pop
podepeek
ser chamado primeiro.No seu caso particular,
peek
aparentemente foi chamado primeiro, o que retornou o valor 40 sem remover o valor da pilha, então apop
chamada remove esse valor da pilha e o retorna, então 40 é impresso nas duas vezes.