In the first block of code, the compiler gives no error. On the other hand, the second block of code gives the error error: 'cin' in namespace 'std' does not name a type.
First block of code:
#include <iostream>
int y;
int main(){
std::cout << "Enter something! \n";
std::cin >> y;
}
Second block of code:
#include <iostream>
int y;
int main(){
std::cout << "Enter something! \n";
}
std::cin >> y;
What causes such a behavior? And can I fix it?
If you need more details, feel free to ask in the comments.
The way C++ works, you can't have executable code outside of a function. When the first block compiles, the compiler looks at the program something like this:
main()"Enter something! \n"ymain() is done now, and there aren't any other functions... Guess the program's over!main() to worry about, so I'm done.The trouble with the second block is that the compiler only gets to step 2. Then it thinks something like:
main() is donemain()?If you're taking a class or teaching yourself C++, you'll come across structs and classes later in your study, and those will make this make a bit more sense. They're an example of the kind of syntax the compiler is trying to interpret this as.
You fail at basic syntax of C \C++.
std::cin >> y; is a statement. Statement aren't allowed outside of function body, only declarations are. Compiler attempts to treat that line as declaration and first token in declaration is a type specifier. Hence you do get that error message.
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