Like Tree1Likes
  • 1 Post By tabstop

Misplaced else

This is a discussion on Misplaced else within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> using namespace std; int main() { int a=4; if(a<4) cout<<"a is smaller than 4"; cout<<a; else if(a==4) ...

  1. #1
    Registered User
    Join Date
    Oct 2013
    Location
    India
    Posts
    39

    Question Misplaced else

    Code:
    #include <iostream>
    
    using namespace std;
    
    
    
    
    int main()
    {
    int a=4;
    
    
    if(a<4)
    cout<<"a is smaller than 4";
    cout<<a;
    else if(a==4)
    cout<<"a is equal to 4";
    else
        cout<<"///etc";
    
    
    }
    i know this error is due to missing brace..but my question is how the compiler manipulate this code.........i mean why it does not execute the statement following if and then remaining code cout<<a; in ordinary procedural way.....ple help



    THANKS.........

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Because any syntax error causes the whole program to be invalid. C is not interpreted; it does not execute line by line until something bad happens.

  3. #3
    Registered User
    Join Date
    Oct 2013
    Location
    India
    Posts
    39
    but how is this a syntax error........is it not like tht for compiler..............like in my code..

    1)check condition..
    1.1) if true....cout<<"a is smaller than 4";
    then cout<<a;
    and the leaving else -if as it........

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    There's no if there for the else to attach to -- once you hit the semicolon on line 14 (as posted), the if has been used up and cannot have any thing else to attach to it. Once you have an unconditionally executed statement, like cout << a in your example (which will always run regardless of the relationship between a and 4), there's no going back to the if and saying "oh wait here's an else".
    Elkvis likes this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Misplaced else in function main -- help?
    By rollyah in forum C Programming
    Replies: 15
    Last Post: 04-30-2010, 01:55 PM
  2. Word even page footers misplaced/offset
    By ulillillia in forum Tech Board
    Replies: 2
    Last Post: 12-13-2008, 08:53 PM
  3. misplaced )
    By blight2c in forum C++ Programming
    Replies: 9
    Last Post: 04-13-2002, 08:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21