Conditional statements

Hi all, I'm new to the forum and C++, and I have learnt all the basics in the last week from reading guides; was just wondering if anyone could help me here as this code doesn't seem to work for me. Any help will be appreciated.

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
int x = 10;
if (x > 0){
cout << "x is positive" << endl;
}


And this is the error message:

fatal error C1075: end of file found before the left brace '{'
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{ 
int x = 10;
if (x > 0){ // since you opened here a brace for your "if-body"
cout << "x is positive" << endl;
} // and close it here
return 0; // and don't forget that
} // you were missing this one to close your main 
You don't have enough closing braces. You have one to close your 'if' statement but not one to close 'main'.

EDIT: Adopting a good indentation style will help you see these kinds of errors:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
    int x = 10;
    if (x > 0)
    {
        cout << "x is positive" << endl;
    }
    return 0;  //main returns an int, 0 is conventional for a successful run
}
Last edited on
*edit*... I derped it!
Last edited on
You don't have to include braces if your 'if' (or while-loop, or for-loop, ...) only encompasses one statement. I tend to use braces anyway for clarity. Clearer code is generally less error prone.
Cool thanks for the help. I'll adopt the writing style as you guys say, but also I was told that "return 0;" isn't needed in C++ because main returns it without the need for the statement, is that correct?
Yes, you don't need a return in main() in C++.
Nobody will blame you if you add that cute "return 0" line tho.
It is better to put it there, because any function that promises a return value (such as main) should really return a value.
Topic archived. No new replies allowed.