Path: utzoo!utgpu!water!watmath!clyde!motown!vilya!lcuxlm!whuts!att!rutgers!mit-eddie!bbn!oberon!sm.unisys.com!aero!venera.isi.edu!lmiller
From: lmiller@venera.isi.edu (Larry Miller)
Newsgroups: comp.lang.c
Subject: Re: Evaluation order of assignment.
Message-ID: <6101@venera.isi.edu>
Date: 17 Aug 88 17:47:04 GMT
References: <957@orion.cf.uci.edu>
Reply-To: lmiller@venera.isi.edu.UUCP (Larry Miller)
Distribution: na
Organization: Information Sciences Institute, Univ. of So. California
Lines: 64

In article <957@orion.cf.uci.edu> schmidt@bonnie.ics.uci.edu (Douglas C. Schmidt) writes:
>Hi,
>
>  Assume the following recursive type declaration for a linked
>list:
>
>struct list {
>   int item;
>   struct list *next;        
>};
>
>Is the following always guaranteed to produce the "intended"
>result:
>
>...
>struct list foo()				(1)
>{						(2)
>   struct list head;				(3)
>   
>   return(head->next = head = (struct list *) malloc(sizeof(struct list)));	(4)
>}						(5)
>...
>
>My intention is to create a dummy node in a circularly-linked list,
>and assign the dummy node's next field to point to the head of
>the list.  Since assignment associates from right-to-left this
>will alway work, right (cryptic style notwithstanding !! ;-)).

[Line numbers added].

Well, let's see, it's not clear what you want to return, an entire structure
(struct list), or a pointer to one.  The usual way that a routine such as this
is written is to return a POINTER to one, so line (1) probably should be
	struct list * foo()

There are several problems at line (4):
	You correctly cast the return from malloc, but you have a type mis-
	match.  head is type (struct list).  You've cast the return from 
	malloc to be a (struct list *).  What you wanted to do was to
	declare head to be a struct list * at line (3):
		struct list  *head;

	Assuming this new correct definition/declaration of head, you still
	risk a NULL return from malloc, so the reference through head to
	head->next could produce an illegal pointer reference through NULL.

	Finally, you're returning head->next, a (struct list *), but you 
	originally declared foo() to return a struct list.

Your explanation of what you want done won't work even with the fixes
described above, since when you're done what you'll get is a pointer
to a (struct list), with its next field pointing back to itself:

+---------+------+
| item    | next +-----+
+---------+------+     |
  ^                    |
  |                    |
  +--------------------+

Larry Miller				lmiller@venera.isi.edu (no uucp)
USC/ISI					213-822-1511
4676 Admiralty Way
Marina del Rey, CA. 90292