This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

tail recursion


Hi!

From the egcs documentation I got the impression that tail recursion
is recognized.  I vaguely recall that I tested this sometime ago, and
it worked.  But in the following little program, neither print_words()
nor free_words() are recognized.  I don't know if this a bug in your
eyes, but it is one in mine :-)

Ah, and

cartan@darkstar:[tst]$ uname -mrs
Linux 2.2.13 i686
cartan@darkstar:[tst]$ gcc --version
egcs-2.91.66
cartan@darkstar:[tst]$

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct word_t {
	struct word_t *next;
	char word[80];
} word_t;

void init_words(word_t **lst)
{
	*lst = NULL;
}

word_t *push(word_t **lst, char *word)
{
	word_t *ret;

	if ((ret = malloc(sizeof *ret))) {
		ret->next = *lst;
		strcpy(ret->word, word);
		*lst = ret;
	}
	return ret;
}

word_t *pop(word_t **lst)
{
	word_t *ret;

	if ((ret = *lst))
		*lst = (*lst)->next;
	return ret;
}

void print_words(word_t *lst)
{
	if (lst) {
		puts(lst->word);
		print_words(lst->next);
	}
}

void free_words(word_t **lst)
{
	if (*lst) {
		free(pop(lst));
		free_words(lst);
	}
}

int main(void)
{
	word_t *lst;

	init_words(&lst);
	if (!push(&lst, "one"))
		return EXIT_FAILURE;
	if (!push(&lst, "two")) {
		free_words(&lst);
		return EXIT_FAILURE;
	}
	if (!push(&lst, "three")) {
		free_words(&lst);
		return EXIT_FAILURE;
	}
	print_words(lst);
	free_words(&lst);
	return 0;
}

Regards,
-- 
Nils Goesche
Ask not for whom the <CONTROL-G> tolls.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]