Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char* initialization

Tags:

c++

This is one usage I found in a open source software.And I don't understant how it works. when I ouput it to the stdout,it was "version 0.8.0".

const char version[] = " version " "0" "." "8" "." "0";
like image 406
逍遥之魂 Avatar asked Mar 27 '12 15:03

逍遥之魂


People also ask

What is const char * used for?

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.

What is a char * const?

char* const is an immutable pointer (it cannot point to any other location) but the contents of location at which it points are mutable. const char* const is an immutable pointer to an immutable character/string.

What is const char * in CPP?

const char *ptr : This is a pointer to a constant character. You cannot change the value pointed by ptr, but you can change the pointer itself. “const char *” is a (non-const) pointer to a const char.

What is the difference between const char * and char * const?

The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).


1 Answers

It's called string concatenation -- when you put two (or more) quoted strings next to each other in the source code with nothing between them, the compiler puts them together into a single string. This is most often used for long strings -- anything more than one line long:

char whatever[] = "this is the first line of the string\n"
    "this is the second line of the string\n"
    "This is the third line of the string";

Before string concatenation was invented, you had to do that with a rather clumsy line continuation, putting a backslash at the end of each line (and making sure it was the end, because most compilers wouldn't treat it as line continuation if there was any whitespace after the backslash). There was also ugliness with it throwing off indentation, because any whitespace at the beginning of subsequent lines might be included in the string.

This can cause a minor problem if you intended to put a comma between the strings, such as when initializing an array of pointers to char. If you miss a comma, the compiler won't warn you about it -- you'll just get one string that includes what was intended to be two separate ones.

like image 120
Jerry Coffin Avatar answered Sep 20 '22 18:09

Jerry Coffin