Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

types

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 a(10);

it works similar to constructor of a class.

like image 384
bjskishore123 Avatar asked Aug 30 '10 14:08

bjskishore123


4 Answers

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.
} 
like image 177
codaddict Avatar answered Nov 15 '22 08:11

codaddict


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
}
like image 44
Chubsdad Avatar answered Nov 15 '22 10:11

Chubsdad


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

like image 3
yfeldblum Avatar answered Nov 15 '22 09:11

yfeldblum


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

like image 1
James Curran Avatar answered Nov 15 '22 09:11

James Curran