Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Simple if/else C++ question

  1. Jan 17, 2009 #1
    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:

    I am sure it is really easy to see, but I do not understand the error :confused:
  2. jcsd
  3. Jan 17, 2009 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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.
  4. Jan 17, 2009 #3
    In other words, write it like this:

    Code (Text):
    if (a < 10)
        y = a*b*c;
        cout << "blah blah" endl;
        y = a+b+c;
        cout << "blah blah" endl;
    The use of the curly brackets and indentation really helps you keep track of whats going on, especially when you are using multiple dependant statements, ie:

    Code (Text):
    if (i > 1)
        if (i = 3)
            cout << "i = 3";
         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: Jan 17, 2009
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Discussions: Simple if/else C++ question
  1. If and else question (Replies: 16)

  2. C++ question (Replies: 2)