struct ? why

Eric S. Raymond eric at snark.UUCP
Sat Oct 15 00:34:58 AEST 1988


(Apologies to C gurus who find this too elementary. But if there's one guy
like this reading the list, there are probably others too intimidated by
the abstruse tone of our usual stuff to post. Let's be nice to novices --
as they are, so once were we...)

In article <315 at hrc.uucp>, dan at hrc.UUCP (Dan Troxel VP) writes:
>Could some of you please give reasons why 'struct'ing variables should be used
>in 'C' programming? What speed increases are noticed if any? Code size at end
>of compile smaller or larger? Things like that.

Structs are provided not for efficiency's sake but in order to permit you to
logically group together data that the program will use together. The classic
example is employee records in a personnel database. Instead of declaring
separate arrays, as in:

	char	name[MAXEMPLOYEES][MAXNAME];	/* employee names */
	int	salary[MAXEMPLOYEES];		/* salaries */

it leads to more readable code to write

	struct employee
	{
		char	name[MAXNAME];	/* employee names */
		int	salary;		/* salaries */
	};

	struct employee people[MAXEMPLOYEES];

and then refer to people[n].name or people[n].salary. This helps you keep
the data organization you're using in mind.

>                                                 I am making major changes to
>some code for my company, and wish to increase the efficiency and readability
>of the code.

Please don't take this as a flame or insult -- but if you don't already 
understand program design well enough to see why structs are useful, you'd
almost certainly be better off farming the job out to someone who does.
-- 
      Eric S. Raymond                     (the mad mastermind of TMN-Netnews)
      UUCP: ...!{uunet,att,rutgers}!snark!eric = eric at snark.UUCP
      Post: 22 S. Warren Avenue, Malvern, PA 19355      Phone: (215)-296-5718



More information about the Comp.lang.c mailing list