Kamil
Kamil

Reputation: 13941

Difference between const char[] Variable; and "some chars"

I have code like this:

const char menu23[] = "2.3. ";
const char menu24[] = "2.4. ";   
const char menu25[] = "2.5. ";  
const char menu26[] = "2.6. "; 
const char menu27[] = "2.7. ";      
const char menu28[] = "2.8. ";  

MenuEntry menu[] = // MenuEntry is a struct
{
    {menu23,  MENU2_OPTIONS, 22, 24, 23,  0,  0,  0}, // 23
    {menu24,  MENU2_OPTIONS, 23, 25,  2,  0,  0,  0}, // 24
    {menu25,  MENU2_OPTIONS, 24, 26,  0,  0,  0,  0}, // 25
    {menu26,  MENU2_OPTIONS, 25, 27,  0,  0,  0,  0}, // 26
    {menu27,  MENU2_OPTIONS, 26, 28,  0,  0,  0,  0}, // 27
    {menu28,  MENU2_OPTIONS, 27, 29,  0,  0,  0,  0} // 28
}

Can I replace it with this?

MenuEntry menu[] = // MenuEntry is a struct
{
    {"2.3. ",  MENU2_OPTIONS, 22, 24, 23,  0,  0,  0}, // 23
    {"2.4. ",  MENU2_OPTIONS, 23, 25,  2,  0,  0,  0}, // 24
    {"2.5. ",  MENU2_OPTIONS, 24, 26,  0,  0,  0,  0}, // 25
    {"2.6. ",  MENU2_OPTIONS, 25, 27,  0,  0,  0,  0}, // 26
    {"2.7. ",  MENU2_OPTIONS, 26, 28,  0,  0,  0,  0}, // 27
    {"2.8. ",  MENU2_OPTIONS, 27, 29,  0,  0,  0,  0} // 28
}

Is there any functional difference?

Upvotes: 1

Views: 271

Answers (2)

zhm
zhm

Reputation: 3651

There is a big difference.

In this problem, first member of MenuItem must be char * type. (Otherwise first version of code in this question will fail with compile errors.)

char menu23[] = "2.3. "; This is a char array. String is stored in array's memory. Its lifetime is the same as array. If it's defined in a function, it will be destroyed after function returns. If it's defined as global variable, then there is no functional difference with second version. (But still different in implement perspective.)

{"2.3. ", MENU2_OPTIONS, 22, 24, 23, 0, 0, 0}, String in this line is a literal constant. It will be stored in memory's static area. Its lifetime will be the same as your application.

Upvotes: 2

tdao
tdao

Reputation: 17713

No differences. The first, though, can be more flexible in case you want to change the name of each menu later on (and in case the constant names are used in multiple locations).

Upvotes: 0

Related Questions