Reputation: 333
I'm a beginner in C++ and I'm doing one of the exercises in Stroustrup's Programming Principles And Practice Using C++
.
This exercise wants me to experiment with legal and illegal names.
void illegal_names()
{
// the compiler complains about these which made sense:
// int double =0;
// int if =0;
// int void = 0;
// int int = 0;
// int while =0;
// string int = "hello";
//
// however, this is legal and it runs without a problem:
double string = 0.0;
cout << string<< endl;
}
My question is, what makes string
different than any other types? Are there other types that is special like string
?
Upvotes: 0
Views: 1544
Reputation: 3209
in C++ std::string
is a defined data type (class), not a keyword. it's not forbidden to use it as variable name. it is not a reserved word. consider a C++ program, which also works:
#include <iostream>
class xxx {
int x;
public:
xxx(int x_) : x(x_) {}
int getx() { return x;}
};
int main()
{
xxx c(4);
std::cout << c.getx() << "\n";
int xxx = 4; // this works
std::cout << xxx << "\n";
return 0;
}
this the same case as with string
. xxx is user defined data type and as you can see it is not reserved.
the image below shows list of reserved keywords in c++.
Upvotes: 0
Reputation: 311010
string
is not a keyword so it may be used as an identifier. All other statemenets in the code segment are erroneous because there are used keywords as identifiers.
As for standard class std::string
then you can even write in a block scope
std::string string;
In this case the identifier string
declared in the block scope will hides type std::string
For example
#include <iostream>
#include <string>
int main()
{
std::string string = "Hello, string";
std::cout << string << std::endl;
return 0;
}
Upvotes: 0
Reputation: 4468
All of those other names are reserved words in the C++ language. But "string" is not. Even though string
is a commonly used data type, it is built out of more basic types and defined in a library which itself is written in C++.
Upvotes: 5