delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/10/11/18:46:11

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: [Q] array declaration
Date: Sat, 11 Oct 1997 13:40:34 -0700
Organization: Alcyone Systems
Lines: 43
Message-ID: <343FE442.53D1A248@alcyone.com>
References: <Pine DOT SUN DOT 3 DOT 91 DOT 971008110125 DOT 28262M-100000 AT is>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Eli Zaretskii wrote:

> I think that saying "extern char array[];", e.g. in the header
> suggested
> by you, is a better solution, since you don't need to mention the
> dimension twice.

This seems to be the best solution (and what is commonly done).  That
is, in the source file, define (and perhaps initialize) the array:

    char array[100] = { /* ... */ };

and in the header, simply declare the array (with defining the size):

    extern char array[];

There is a precisely analogous situation here to functions and
prototypes.  Prototypes (declarations) go in the header; definitions
(the function bodies) go in the source files.  (The only clear
difference is that, with prototypes, the `extern' keyword is not
required, but is certainly allowed.)

As for knowing the size of the array outside of the source file in which
the array is defined, you can do that with const int external, e.g., in
the source:

    char array[100] = { /* ... */ };
    const int arraySize = sizeof array/sizeof array[0];

and in the header:

    extern char array[];
    extern const int arraySize;

One can obviously use a #define, as well.

-- 
          Erik Max Francis, &tSftDotIotE / mailto:max AT alcyone DOT com
                        Alcyone Systems / http://newton.alcyone.com/
   San Jose, California, United States / icbm://+37.20.07/-121.53.38
                                      \
   "After each war there is a little / less democracy to save."
                                    / Brooks Atkinson

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019