Author Topic: else command does not work  (Read 418 times)

Offline sirhakonik

  • Single posting newcomer
  • *
  • Posts: 1
else command does not work
« on: July 23, 2019, 05:06:56 pm »
While using codeblocks, i've noticed a bug, that when coding:
#include <iostream>
using namespace std;
string PIN;
int main()
{
    cout << "Hello!";
    cout<<endl <<"insert PIN:";
    cin>> PIN;
    if(PIN=="2137");
    {
    cout<<"PIN Correct";
    }
    else;
    {
    cout<<"PIN Incorrect";
    }
    return 0 ;

when i press f9 my program does not work, and i see "error: else without previous if".
 Is there way to repair it?

Offline stahta01

  • Lives here!
  • ****
  • Posts: 6645
    • My Best Post
Re: else command does not work
« Reply #1 on: July 23, 2019, 05:18:42 pm »
Please read the rules and find a website to ask your programming questions on.
http://forums.codeblocks.org/index.php/topic,9996.0.html

Note: Putting an semi colon after else is wrong!

Tim S.
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.
--
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org

Offline sodev

  • Regular
  • ***
  • Posts: 327
Re: else command does not work
« Reply #2 on: July 23, 2019, 06:52:31 pm »
While browsing the forum, i noticed a bug, it's written after sirhakonik ;D

Well, i couldn't resist, i had to write this.

Note: Putting an semi colon after else is wrong!

I couldn't resist to answer this one as well, this is actually wrong :). Of course you can write a semicolon after the else, this is just the shortcut to create an empty else case, you could also do this by opening an empty block with parentheses.

It's not even an error to put the semicolon after the if, the effect is the same, the error however is that extra block between the if and else, with the semicolon after the if this results into two blocks of code between the if and else, and that is the error, there can be only one ;).

Looks like i have smart-ass-day today ::)

Offline raynebc

  • Almost regular
  • **
  • Posts: 212
Re: else command does not work
« Reply #3 on: July 24, 2019, 07:23:18 pm »
Even in the case of being pedantic, I have to disagree.  stahta01 didn't say it can never be used, in the case of this code example he said it was wrongly used here and is why the program isn't behaving as is wanted.

Offline sodev

  • Regular
  • ***
  • Posts: 327
Re: else command does not work
« Reply #4 on: July 24, 2019, 08:16:44 pm »
Dammit, i got beaten, how could i miss that?

Ok, you two are right, the semicolon after the else is an error because it is causing unwanted behavior. I am right that the semicolon after the if is causing the compile error, plus it is causing unwanted behavior.

So we are all right, what did we win ;D?