0

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?

3
  • string isn't a keyword. Commented Aug 9, 2014 at 19:15
  • as chris said, string isn't special, and that's the special thing about it. Commented Aug 9, 2014 at 19:25
  • There are keywords and names in the namespace std (none of the names, introduced in the namespace std, is a keyword) Commented Aug 9, 2014 at 19:28

3 Answers 3

5

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++.

Sign up to request clarification or add additional context in comments.

1 Comment

Furthermore, the string type is declared in namespace std, so even an #include <string> would not produce a conflict.
0

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;
}

Comments

0

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++. enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.