C++ if/else syntax error in beginner program

  • Topic: C/C++ 
  • Thread starter Saladsamurai
  • Start date
  • Tags Tags
    C++
2 replies · 15K views · last reply
Saladsamurai
Messages
3,009
Reaction score
7
What is wrong with mine? I am super new to programming and am trying to figure this stuff out on my own. The stuff in the tutorial is even too advanced for me.

Here it is:
Screenshot of the Dev-C++ 4.9.9.2 editor showing if_else.cpp, with an if (a < 10) y = a*b*c; line followed by a stray else { y = a + b + c; } on a later line, and the compiler message window listing expected primary-expression before else errors.


I am sure it is really easy to see, but I do not understand the error :confused:
 
The else statement has no if statement immediately preceding it.

The proper syntax is

if (boolean) statement else statement

You have

if (boolean) statement statement else statement


A simple rule that I use: Always use block statements (i.e., statements enclosed in braces) with an if statement, and never put the statement on the same line as the if. While C and C++ do allow simple statements after an if (or else), many organizations have programming rules that make this construct illegal. The cost of always using the block construct costs is a few extra keystrokes (there is zero performance penalty). The benefits are immense: It is clearer, there is a much reduced chance of introducing a bug, and you can insert break points on the if (or else) statement.
 
In other words, write it like this:

Code:
if (a < 10)
{
    y = a*b*c;
    cout << "blah blah" endl;
}
else
{
    y = a+b+c;
    cout << "blah blah" endl;
}

The use of the curly brackets and indentation really helps you keep track of what's going on, especially when you are using multiple dependent statements, ie:

Code:
if (i > 1)
{
    if (i = 3)
    {
        cout << "i = 3";
    }
}
else
{
     cout << "i is less than or equal to 1";
}

You also put parenthesis around the statement after else, which is not correct. Else does not make a test like if and else if does. Basically when you put something in parenthesis after if or else if you are saying if whatever is in the parenthesis is true, then do whatever is next. The statement inside of the parenthesis is not even testable, on second glace.
 
Last edited: