#include <iostream>
using namespace std;
int main ()
{
double testscore;
cout << " Enter your test score and i will tell you the letter grade you earned ";
cin >> testscore;
switch (testscore)
{
case (testscore < 60.0):
cout << "your grade is F.\n";
break;
default:
cout << "that score isnt valid\n.";
}
return 0;
}
views:
161answers:
7
+3
A:
There's several problems:
You're missing a closing brace
}at the end ofmain(). Not sure if that was intentional, or a cut-and-paste error.The
returnis inside theswitchstatement, which means the non-default case will not return the function. Since the function returns anint, this will result in a compilation error.You cannot switch on expressions like that. Use an
ifstatement instead.
LeopardSkinPillBoxHat
2010-02-22 06:51:52
Not entirely accurate. Firstly, in C++ a missing `return` statement in a value-returning function is undefined behavior, not a compilation error. Secondly, returning from `main` without an explicit `return` statement is explicitly allowed and defined by the language as equivalent to returning 0.
AndreyT
2010-02-22 07:58:13
@AndreyT: Not entirely accurate. A value-returning function *must* contain a return statement! I'm assuming VC++ isn't non-compliant in this regard: **error C4716: 'foo' : must return a value**
2010-02-22 14:31:26
@STingRaySC: Well, 6.6.3/2 clearly states that "Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function". As I understand, issuing a diagnostic message during translation and terminating translation is a valid way to react to UB-producing code, so there's no reason to say that VC++ is non-compliant in this case. Comeau, on the other hand, issues a mere warning.
AndreyT
2010-02-22 14:58:24
A:
Some syntax errors and the main point that switch in C can only be used for integer and bool stuff.
#include <iostream>
using namespace std;
int main ()
{
double testscore;
cout << " Enter your test score and i will tell you the letter grade you earned ";
cin >> testscore;
if (testscore < 60.0) {
cout << "your grade is F.\n";
}
else {
cout << "that score isnt valid\n.";
}
return 0;
}
Totonga
2010-02-22 07:41:23
A:
switch expects integer expression in the parenthesis which is not the case in your program. Also each case should be integer or constant character expression.
Adil
2010-02-22 07:43:51