Find the size of an array

B

Ben Bacarisse

Bartc said:
These points probably already mentioned but to summarise:

"const int x" means something like "readonly int x", except x can be
initialised and can be written to if you try hard enough.

Such a summary should add that modifying a const-qualified object
(like x) is undefined behaviour. You can try, but you should not do
it.
And a compiler usually can't treat it as a compile-time constant, even when
you clearly initialise it, as in for example: const int x = 1200.

To declare a proper named integer constant as in Pascal for example, you
must use:

#define x 1200

or:

enum {x = 1200};

But in both of these cases the scope of x is the entire scope of the file.
And in the enum case, x can only be an integer.

So C doesn't have proper localised named constants. (Which can be a little
frustrating as it would have been a really easy addition to the language:
properconst int asize=sizeof arrc/sizeof arrc[0]; )

That's a little misleading. If the enum is at blocks scope the names
in it are limited to that scope. Since your example above tries to
make asize and int, then a localised enum is up to the job. Had your
example been const size_t = ... then I agree, there is no localised
equivalent.
 
B

Bartc

That's a little misleading. If the enum is at blocks scope the names
in it are limited to that scope. Since your example above tries to
make asize and int, then a localised enum is up to the job.

OK, I didn't know that. So for most purposes it's possible to use:

#define const_int(name,value) enum {name=value}

Then create integer constants with:

const_int (length, sizeof (a)/sizeof(a[0]);

without worrying about re-use of 'length'. That is, where the use of 'enum'
seems inappropriate.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top