简体   繁体   中英

Passing an all-caps variable to a const char array pointer in C

A const char * array in C is often formatted like this:

const char *my_array[] = {
   "array1",
   "array2",
   "array3"
};

Some programmers pass an all-caps variable to the array like this:

const char *their_array[SOME_VARIABLE] = {
    "ARRAY_1",
    "ARRAY_2",
    "ARRAY_3"
};

What is the all-caps variable? What are the advantages or disadvantages of using it?

Thank you

What is the all-caps variable?

It's probably a macro name. Somewhere else there's probably a line like

#define SOME_VARIABLE 3

So the line

const char *their_array[SOME_VARIABLE] = { ...

is just as if you had written

const char *their_array[3] = { ...

What are the advantages or disadvantages of using it?

  1. If you write const char *their_array[] = {... , the compiler automatically figures out the size of the array for you (if it can), based on the number of initializers you give it.

  2. If you write const char *their_array[3] = {... , you're telling the compiler exactly how big you want the array to be, and there's a potential contradiction if you give it a different number of initializers. If you give it exactly three initializers, everything is fine. if you give it fewer than three initializers, the compiler will automatically initialize the rest to 0 (or in this case, to null pointers). And if you give it more than three, the compiler will complain.

  3. If you write const char *their_array[SOME_VARIABLE] = {... , it's the same, but you have the advantages of using a name SOME_VARIABLE instead of a "magic number" 3. Perhaps the name SOME_VARIABLE will help the reader understand what the number 3 means. Perhaps you can use the name SOME_VARIABLE somewhere else (like in a loop for(i = 0; i < SOME_VARIABLE; i++) ). For these and other reasons it's usually (though not absolutely) considered a good rule to use named constants rather than "magic numbers".

Macro names are traditionally written in all caps to remind everyone that they are macro names, since macro names are special; they're not true variables.

If you have never encountered these "all-caps variables" before, you'll want to go and read the chapter in your C textbook on "The C Preprocessor".

Specifying he size in that case doesn't really matter, the compiler can infer the size from the initialization. However, static keyword makes a different. You can think of static as if the variable was global, but is only accessible from its scope. (Btw, I think you're missing an equal sign in your code)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM