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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With