Else statement always runs

This is the first time posting to the forums. I think that there is something that I just do not understand about if and else statements. It seems on the forums another guy had a similar issue with them but I didn't understand the answer. I do not know why my last "else" statement will always run. I've tried everything I can think of and I'm not having any luck. I have a feeling that I can't chain that many else if conditions together but I can't figure out why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//Calculating Pay and Hours
#include <conio.h>
#include <iomanip>
#include <iostream>
using namespace std;


int main()
{
	//variables

	float hoursworked, overtimehours, payrate, regpay, overtimepay;
	float grosspay, fedtaxes, statetaxes, netpay;
	string lastname, firstname, idnumber;
	
	//Identifing the worker
	
	cout << "Last Name of the employee: ";
	cin >> lastname;
	cout << "\nFirst Name of the employee: ";
	cin >> firstname;
	cout << "\nEmployee I.D. number: ";
	cin >> idnumber;
	
	//calculating the hours worked and overtime hours worked
	
	system ("cls");
	
	cout << "How many hours did " << lastname << ", " << firstname << " work this week? (between 1 and 60)  ";
	cin >> hoursworked;
		{
			if (hoursworked <= 0)
				{
					cout << "\nEmployee must work more than 0 hours to be paid, program will end ";
					return 0;
				}
			else if ((hoursworked > 1) && (hoursworked <= 40))
				{
					hoursworked = hoursworked;
				}
			else if ((hoursworked > 40) && (hoursworked < 60))
				{
			
					 cout << "Maximum hours is 40 normal pay hours the extra hours will be applied to overtime pay ";
					 hoursworked = 40;
					 overtimehours = hoursworked - 40;
				}	  
				
			
			else (hoursworked > 60);
				{
					cout << "\nMaximum hours a worker can work is 60, the program will end. ";
					return 0;
				}
			
		}
	
It's because of the semi-colon on line 50.

else (hoursworked > 60);

Basically, that semi-colon indicates that the else control structure should do nothing.

Therefore, the braces on lines 51 and 54 aren't associated with the else on line 50, and will always execute.
Last edited on
Hey xismn thanks for the quick reply. I kinda was leaning in that direction however, if I take the semi-colon out it will not compile. It throws an error saying "expected ';' before '{' token." I am not sure what that error means.
Hi MRangel

An else statement cannot have a condition, make it an else if instead. Use else to catch error conditions.

:+)
Last edited on
Hey TheIdeasMan. Thanks for your reply and I could have sworn that I tried that already! It is finally working! Thanks again.
Topic archived. No new replies allowed.