On Sep 9, 9:38 pm, vaclavp...@atla s.cz wrote:
I have a question on constant variables.
/////////////////////////////////////////////
//
#include <cstdlib>
#include <iostream>
using namespace std;
const static char* STATIC_CONST_NA ME = "Hello";
This is a legal, but a very unusual way of declaring the
variable. Storage specifiers (static, extern, etc.) always come
first. (According to the C99 standard, "The placement of a
storage-class specifier other than at the beginning of the
declaration specifiers in a declaration is an obsolescent
feature." Formally, this doesn't affect C++, but practically,
putting static anywhere but at the beginning of a declaration
causes confusion for the readers.)
const char* CONST_NAME = "Hello";
int main(int argc, char *argv[])
{
cout << STATIC_CONST_NA ME << endl;
cout << CONST_NAME << endl;
system("PAUSE") ;
return EXIT_SUCCESS;
}
Can anybody explain to me different between (const static
char*) and (const char*) ?
As others have pointed out, the difference here is linkage, and
it has nothing to do with the const here. Your program doesn't
have any const variables; only non-const variables which point
to const.
Note that the default linkage of a const variable is internal,
so:
char const* const name1 = "..." ;
has internal linkage, even without the "static". To give it
external linkage, you need the keyword "extern", e.g.:
extern char const* const name1 = "..." ;
In summary:
// declaration linkage
// -----------------------------------------------------
char const* name1 = "..." ; // external
static char const* name2 = "..." ; // internal
extern char const* name3 = "..." ; // external
char const* const name1 = "..." ; // internal
static char const* const name2 = "..." ; // internal
extern char const* const name3 = "..." ; // external
(And I know, it's not consistent. But hey, that's C++.)
--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34