Does GCC perform Tail call optimization on the following function?
bool isEqual(Node *head1, Node *head2)
{
if(head1 == NULL || head2 == NULL)
return head1 == NULL && head2 == NULL;
return head1->data == head2->data && isEqual(head1->next, head2->next);
}
Yes it does, at least the way I compiled it. The assembly code for that function was
isEqual(Node*, Node*):
test rdi, rdi
sete dl
test rsi, rsi
sete cl
mov eax, ecx
or al, dl
jne .L2
mov edx, DWORD PTR [rsi+8]
cmp DWORD PTR [rdi+8], edx
je .L5
rep ret
.L2:
mov eax, ecx
and eax, edx
ret
.L5:
mov rdi, QWORD PTR [rdi]
mov rsi, QWORD PTR [rsi]
test rdi, rdi
sete dl
test rsi, rsi
sete cl
mov eax, ecx
or al, dl
jne .L2
mov ecx, DWORD PTR [rsi+8]
cmp DWORD PTR [rdi+8], ecx
je .L5
rep ret
That's clearly a loop, and no nested calls appear.
You should verify whether it does something similar with your version of GCC on your platform and with your compilation options.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.