开发者

Why string string is allowed and int int is not allowed by Compiler?

开发者 https://www.devze.com 2023-01-14 07:34 出处:网络
I am just trying to check whether compiler allows type name as variable name. When i tried int int; It reported an error saying

I am just trying to check whether compiler allows type name as variable name. When i tried

int int;

It reported an error saying

error C2632: 'int' followed by 'int' is illegal

But when i tried

#include <string>
using namespace std;

int main()
{
    string string;
}

It didn't give any error. Both string and int are data types.

Why compiler allows string and doesn't allow int ?

EDIT: includes updated.

EDIT: Some people are saying that int is not a class. In that case, why below line is allowed.

int开发者_JAVA技巧 a(10);

it works similar to constructor of a class.


string is not a C++ reserved word, but int is, and a reserved word cannot be used as an identifier.

And its syntactically fine to have class name and object name to be same.

class test {}; 
int main() { 
        test test; // test is an object of type test.
} 


int is a C++ keyword. In the second declaration 'string string' declares an object of type 'std::string'. After this the name 'string' hides 'std::string' in an unqualified lookup

#include <string>
using std::string;

int main(){
    string string;

    string s;  // Error
}


int is a keyword, whereas string is the name of a class in the standard library but is not a keyword.


string isn't actually a "data type" in the same sense the int is. int is a "native type" and as such, the text "int" is a keyword.

string is just a "user-defined" class (although, here the "user" the defined it is the C++ standards committtee). But as such, "string" is not a keyword.

So int int is two keywords together, but string string is just defining a varaible named "string" of type "string". The C++ compiler can keeps the separate two uses of "string" straight (but it's not a good idea to do this, since, as you've demonstrated, programmers often can't).


Well, given that others have essentially posted the answer, I'm going to go ahead and post what I meant...

I'm assuming that because the second answer compiles, that you have using namespace std; in your file (which is in general not a good idea; I fail to see why people tell beginning C++ users to do this).

When the compiler goes to resolve the first string, it is able to find the class in namespace std. The second use of string is simply the name of the variable.


The compiler allows primitive types to behave like classes for the purposes of templates - if you had to specialize for primitives everywhere it would be a nightmare.


Try removing

#include <string>
0

精彩评论

暂无评论...
验证码 换一张
取 消