Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!usc!apple!amdahl!lamont From: lamont@uts.amdahl.com (Duane Richard LaMont) Newsgroups: comp.lang.c Subject: Re: doing nasty things with internal static variables Keywords: C, crossreference Message-ID: <78hW01XR47Gy00@amdahl.uts.amdahl.com> Date: 22 Mar 91 05:44:38 GMT References: <1991Mar19.164037.7421@intellistor.com> <1991Mar19.183920.18911@rice.edu> Reply-To: lamont@amdahl.uts.amdahl.com (Duane Richard LaMont) Distribution: usa Organization: Amdahl Corporation, Sunnyvale CA Lines: 43 In article <1991Mar19.183920.18911@rice.edu> fontenot@comet.rice.edu (Dwayne Jacques Fontenot) writes: >I have found myself doing this because it works, but I am curious if it >is a common practice or if it is highly likely to get me into trouble: > >char *foo() >{ > static char string[64]; > > ... > return(string); >} Thus far, the followups to the posting above have focused on the fact that this method works and is common practice, etc. However, I would like to point out one caveat which I've experienced. I once wrote a function like foo which returned different strings based on the value of a lone argument. One of my less experienced co-workers attempted to use it and did something like this: char *a, *b; a = foo(x); b = foo(y); printf("a = %s; b = %s\n", a, b); Much to her surprise, string a was always identical to string b regardless of the values of x and y. I pointed out that a and b both pointed to the static buffer within foo which was overwritten on each call. So, I was feeling pretty good about myself until the next week when I wrote something like this: bar(foo(x), foo(y)); My new rule of thumb: If the higher level application programmer is likely to call my function multiple times and save the results separately, make him pass in his own buffer. This saves him from making calls to strcpy. Also note that, at least on my system, asctime uses a static return buffer and has this caveat listed on the man page. Rick LaMont