Question

I was wondering what works best in terms of performance? Is it better to have that

char ar1[5] = "work";
char ar2[5] = "flue";
/*...*/
char ar50[6] = "alias";

Or is it more efficient to have everything in #define:

#define ar1 "work"
#define ar2 "flue"
/*...*/
#define ar50 "alias"

or does it make any difference at all?

NOTE: Iff your not manipulating these strings,changing arrays values etc., only using them to get their value.

Was it helpful?

Solution

const char ar1[5] = "work";
const char ar2[5] = "flue";
/*...*/
const char ar50[6] = "alias";

You should prefer the above style rather than the other one. I find the following reason to do it in this way.

  1. There is type and size associated with these array variables. So there would be better type safety in your program.

  2. This version makes program easier to read and understand and debug by others. This is very important attribute and we should consider while writing any software.

  3. There is no standard defined for macro/#define so different compiler is free to choose the different strategy while expanding these in your program. There could be one copy for each time the literal appears in source code, or one master copy shared among the \ instances.

EDIT

As you have mentioned that you would just be reading these strings in your program, it is really good idea to make it const.This also clearly shows the intent of the programmer to the reader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top