how come when you output numbers you don't need to add quotation marks around them and strings you do? for example:
cout << 2003; would be alright but
cout << coolness; would signal an error
what's the difference between a number and a word?
Printable View
how come when you output numbers you don't need to add quotation marks around them and strings you do? for example:
cout << 2003; would be alright but
cout << coolness; would signal an error
what's the difference between a number and a word?
when you want to cout<< a word, the compiler assumes it is somekind of a variable, but because it does not see it defined/initialized anywhere in the code it returns an error.
The reason that you could cout an integer is because no variables can start with a digit. You cannot have int 123 = 0;
I'm pretty sure that there are some other reasons for this accurence, but this is the best explanation that i could think of.
axon
That's just how compilers work man. Think about it. What if there wasn't that rule:
char * s = hello world! This is 10 % of my program - woohoo!;
The compiler would have quite a chore figuring out whether it was looking at a syntax error or a sentence.
But moreover, a string literal is a human friendly representation of an array of numbers:
All three arrays contain the exact same values. The last one is just easier for humans to type.Code:int array[] = { 72, 73, 0 };
char buff[] = {72, 73, 0};
char str[] = "HI";
If only the US government thought things through as well as the ISO people. :D
A single variable can hold only a single number. To store a string, you need an array (or "string") of numbers. And, to make things even more interesting, the ASCII code for the character 1, is not 1, it's 49.
'1' = 49 ASCII code for the character 1
"1" = [49, 0] An array... ASCII "1" with null-termination.
So, although cout << 123; and cout << "123"; will produce the same results, 123 and "123" are not the same... the first is a single number, the second is an array of four numbers (including the null termination.)
The use of quotation marks to differentiate between variables and literals is common to many (most?) computer languages. I have only seen the use of 'single quotes' in C and C++. But, I haven't studied that many languages.
(Using the above posts for background information)
The operator << for std::cout is overloaded to take many variable types. When you go std::cout << (int), it will interpret the variable as an int and so it will convert it to a string of characters and then output THAT to the screen.