c++ switch [Error] 'x' cannot appear in a constant-expression - c++

im trying to execute this script its for my university
int main()
{
int x;
double y;
Provo:
cout<<"Vlera e X: ";
cin>>x;
switch(x)
{
case ((x)<(0.9)):
y=x*x;
break;
case (x==0.9):
y=2*x;
break;
case 'x>0.9':
y=x-3;
break;
}
cout<<"\n\n";
return 0;
}
this is teh code and the error is:
17 10 ....\Untitled1.cpp [Error] 'x' cannot appear in a constant-expression
someone help please?

I think you have misunderstood how to use the switch statement. switch is used to branch your code based on the condition, in your case x, taking different integral values. It is not suitable for use with double values like you do.
A correct switch expression would look like:
switch(x)
{
case 1:
y=x*x;
break;
case 2:
case 3:
case 4:
y=2*x;
break;
case 5:
y=x-3;
break;
}
To accomplish what you want, use if else instead, for example:
if (x < 0.9) {
y=x*x;
else if(x == 0.9) {
y=2*x;
} else {
y=x-3;
}
However, comparing floating point values for equality is a bad idea. It is usually better to do something like:
double epsilon = <some small value>;
if (x < 0.9-epsilon) {
y=x*x;
else if(x > 0.9+epsilon) {
y=x-3;
} else {
y=2*x;
}

Related

How to build the simple change maker for a vending machine?

On the menu deposits n,d, q, o,f are indicated which are indication for nickel dime quarter , one dollar and five dollar. I should also indicate "C" as in cancel option when the user hits c. But i couldn't make it work. My program still runs even the user hit c. I am confused on this point?
switch(DepositIndication) {
case 'n': {
PurchasedPrice=PurchasedPrice-0.05;
NumOfNickels=NumOfNickels+1;
}
break;
case 'd': {
PurchasedPrice=PurchasedPrice-0.10;
NumOfdimes=NumOfdimes+1;
}
break;
case 'q': {
PurchasedPrice=PurchasedPrice-0.25;
NumOfquarters=NumOfquarters+1;
}
break;
case 'o': {
PurchasedPrice=PurchasedPrice-1.00;
NumOfOnes=NumOfOnes+1;
}
break;
case 'f': {
PurchasedPrice=PurchasedPrice-5.00;
NumOfFives=NumOfFives+1;
}
break;
}
the condition c is missing and I Put the break into to brackets;
switch (DepositIndication) {
case 'n':
{
PurchasedPrice = PurchasedPrice - 0.05;
NumOfNickels = NumOfNickels + 1;
break;
}
case 'd':
{
PurchasedPrice = PurchasedPrice - 0.10;
NumOfdimes = NumOfdimes + 1;
break;
}
case 'q':
{
PurchasedPrice = PurchasedPrice - 0.25;
NumOfquarters = NumOfquarters + 1;
break;
}
case 'o':
{
PurchasedPrice = PurchasedPrice - 1.00;
NumOfOnes = NumOfOnes + 1;
break;
}
case 'f':
{
PurchasedPrice = PurchasedPrice - 5.00;
NumOfFives = NumOfFives + 1;
break;
}
case 'c':
}
//you can print cancellation messages in here
break;
}
default:
break;
}
I should also indicate "C" as in cancel option when the user hits c
Your current code works fine the only thing you are missing to make that work right now is a default case or a case where you specifically check if the user inputed C.
Example:
switch(DepositIndication) {
// All other cases ...
case 'c': {
// The user canceled the interaction
std::cout << "Interaction was canceled." << std::endl;
break;
}
// Default case to ensure that even,
// if the user hits any other key we still handle his interaction
default {
std::cout << "No fitting interactional behaviour found." << std::endl;
break;
}
}
If you want to ensure that the user can even input big lettered chars and the switch case will still work you can use std::tolower and cast it back to a char.
Make the User-Input lowercase:
// Make DepositIndication lowercase
DepositIndication = std::tolower(DepositIndication, std::locale());

How to construct a class with variadic pointer functions as members?

I want to know whether the following is possible in C++. I need to construct a class that will store as a data member a std::map, with keys being of type std::string, and values being function pointers. The thing is that I want these function pointers to be variadic in the sense that they should point to functions accepting an arbitrary number of arguments, i.e. pointing to functions of the form
template<class... Args>
f(Args...);
The important bit is that I want to be able to have different arguments for the different function pointers in the map of a given instance of my class. For example, I might want to create an object of my class and have its map contain two pairs, one corresponding to a function having (double, int) as arguments, and another having (std::vector, int, int) as arguments. And I want to be able to make this general, in the sense that I want to be able to add new elements to the map, with possibly different argument lists (although I would only do this at compile-time, I still need to code the class without knowing about the types since I want to add the new elements from other files/clients).
What is the best way to implement this?
For all those saying you cant, you actually can, it's not pretty:
This is an example code from the output of the moc tool, that does exactly that: It stores an arbitrary amount of function / method pointers, with an arbitrary number of arguments.
Easiest Solution: Just use Qt's moc tool to generate that for you,
If you cannot or don't want to use Qt, you still can analize the code below on how they achieve it.
int AtCore::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 25)
qt_static_metacall(this, _c, _id, _a);
_id -= 25;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 25)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 25;
}
return _id;
}
void AtCore::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
AtCore *_t = static_cast<AtCore *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->printProgressChanged((*reinterpret_cast< const float(*)>(_a[1]))); break;
case 1: _t->receivedMessage((*reinterpret_cast< const QByteArray(*)>(_a[1]))); break;
case 2: _t->stateChanged((*reinterpret_cast< PrinterState(*)>(_a[1]))); break;
case 3: _t->print((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 4: _t->stop(); break;
case 5: _t->pause((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 6: _t->resume(); break;
case 7: _t->home((*reinterpret_cast< uchar(*)>(_a[1]))); break;
case 8: _t->home(); break;
case 9: _t->setExtruderTemp((*reinterpret_cast< uint(*)>(_a[1])),(*reinterpret_cast< uint(*)>(_a[2]))); break;
case 10: _t->setExtruderTemp((*reinterpret_cast< uint(*)>(_a[1]))); break;
case 11: _t->setExtruderTemp(); break;
case 12: _t->move((*reinterpret_cast< uchar(*)>(_a[1])),(*reinterpret_cast< uint(*)>(_a[2]))); break;
case 13: _t->setBedTemp((*reinterpret_cast< uint(*)>(_a[1]))); break;
case 14: _t->setBedTemp(); break;
case 15: _t->setFanSpeed((*reinterpret_cast< uint(*)>(_a[1])),(*reinterpret_cast< uint(*)>(_a[2]))); break;
case 16: _t->setFanSpeed((*reinterpret_cast< uint(*)>(_a[1]))); break;
case 17: _t->setFanSpeed(); break;
case 18: _t->setAbsolutePosition(); break;
case 19: _t->setRelativePosition(); break;
case 20: _t->setPrinterSpeed((*reinterpret_cast< uint(*)>(_a[1]))); break;
case 21: _t->setPrinterSpeed(); break;
case 22: _t->setFlowRate((*reinterpret_cast< uint(*)>(_a[1]))); break;
case 23: _t->setFlowRate(); break;
case 24: _t->close(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (AtCore::*_t)(const float & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&AtCore::printProgressChanged)) {
*result = 0;
return;
}
}
{
typedef void (AtCore::*_t)(const QByteArray & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&AtCore::receivedMessage)) {
*result = 1;
return;
}
}
{
typedef void (AtCore::*_t)(PrinterState );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&AtCore::stateChanged)) {
*result = 2;
return;
}
}
}
}

C++: Using multiple conditions in switch statements

I am in a beginning C++ programming class and I need help with nesting switch statements and using multiple conditions, because I have to translate a program I already wrote from if/else statements to switch statements, because I didn't know I was supposed to use the switch statement.
For example, how do I change something like:
if (temperature >= -459 && temperature <= -327)
{
cout << "Ethyl Alcohol will freeze.\n";
}
else if (temperature >= -326 && temperature <= -30)
{
cout << "Water will freeze.\n";
}
else if ...
{
}
else
{
}
Into a switch/case statement? I can get the first level, but how do I nest and have multiple conditions like the temperature statements above?
Switch statements work like this:
int variable = 123; // or any other value
switch (variable)
{
case 1:
{
// some code for the value 1
break;
}
case 12:
{
// some code for the value 12
break;
}
case 123:
{
// some code for the value 123
break;
}
case 1234:
{
// some code for the value 1234
break;
}
case 12345:
{
// some code for the value 12345
break;
}
default:
{
// if needed, some code for any other value
break;
}
}
First of all, this question is in C and not in C++. C++ inherited most of the C language, including the switch-case.
You can't do this with a switch, unless you start enumerating all the values one by one, like this:
switch (temperature) {
case -459:
case -458:
....
case -327: <do something>; break;
case -326:
.....
}
This is because in C, switch-case is simply translated to a series of if-goto statements, with the cases just being the labels.
In your case, your stuck with an if-else-if ladder.
You could use a lookup table that has temperatures and the text to print:
struct Temperature_Entry
{
int min_temp;
int max_temp;
const char * text_for_output;
};
static const Temperature_Entry temp_table[] =
{
{-459, -327, "Ethyl Alcohol will freeze.\n"},
{-326, -30, "Water will freeze.\n"},
};
static const unsigned int entry_count =
sizeof(temp_table) / sizeof(temp_table[0]);
//...
int temperature;
for (unsigned int i = 0; i < entry_count; ++i)
{
if ( (temperature >= temp_table[i].min_temp)
&& (temperature < temp_table[i].max_temp))
{
std::cout << temp-table[i].text_for_output;
}
}
As many have pointed out, you cannot use switch case for ranges and dynamic formulas. So if you want to use them anyway, you will have to write a function which takes a temperature and returns a temperature range out of a pre-known set of temperature ranges. Then, finally, you can use a switch/case for the temperature ranges.
enum TemperatureRange { FrigginCold, UtterlyCold, ChillinglyCold, Frosty, ... };
TemperatureRange GetRange( int temperature );
// ...
switch( GetRange( temperature ) )
{
case FrigginCold: cout << "The eskimos vodka freezes."; break;
case UtterlyCold: cout << "The eskimo starts to dress."; break;
// ...
}

how to use enum inside a switch condition

The following code uses a switch with enum. The main program passes the argument correctly to the function, but the correct switch line is not executed. Can you advise why it is not entering the switch conditions?
enum MyEnum {
Enum1 = 1,
Enum2 = 0x0D
};
bool compute(MyEnum code) {
switch(code) {
Enum1: return true;
Enum2: return false;
};
cout << "why here??" << endl; // this line is getting printed for both inputs
return false;
}
int main() {
cout << "compack=" << compute((MyEnum)1) << endl; // printed "0"
cout << "compack=" << compute((MyEnum)13) << endl; // printed "0"
}
I checked the other questions related to switch and enum (eg 3019153), but cant figure out the bug.
You are missing the case keyword:
switch(code) {
case Enum1: return true;
case Enum2: return false;
};
switch(code)
{
case Enum1: return true;
case Enum2: return false;
};
You forgot to write case
switch(code)
{
case Enum1: return true;
case Enum2: return false;
};
A generic switch is like:
switch(var)
{
case val1:
foo();
break;
case val2:
bar();
break;
default:
error();
};
You forgot case there..
switch(code)
{
case Enum1:
//do something
break;
case Enum2:
//do something
break;
};
Okay, so others have answered that you are missing the case keyword. What hasn't been explained, though, is why the original code compiled. That's because without the case keyword, it was treated as a goto label. In fact, this compiles:
switch (i) {
if (j == 3) {
case 1:;
L1:;
} else {
goto L1;
case 2:;
}
}
Note that the j==3 is actually dead code. It can never be executed. For an actual useful application of this, see Duff's device. By the way, compiling with full warnings enabled would have warned you about an unused goto label, at least with g++ and clang++ (-Wall -Wextra -pedantic).

I wanted to know how to properly use switch/case

I was just wondering if someone could just give me an example of how to use switch/case. I kinda get the just of it but am having trouble figuring out what and how i can use this. Thank you in advance.
There are couple of things to remember about switch case statements:
a) The condition should be integeral/enum/user defined type which supports conversion to int or enum
b) case lables are compile time constants
c) No two case label expressions can have the same value
d) $6.4.2/5- "When the switch statement is executed, its condition is evaluated and compared with each case constant. If one of the case constants is equal to the value of the condition, control is passed to the statement following the matched case label. If no case constant matches the condition, and if there is a default label,control passes to the statement labeled by the default label. If no case matches and if there is no default then none of the statements in the switch is executed."
e) $6.4.2/6- "case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels. To exit from a switch, see break"
enum direction {north, south, east, west};
char x;
class UD{
operator int(){return 0;}
};
direction f1(){
return north;
}
char f2(){
return 'A';
}
int main(){
direction d = f();
string country;
// switch condition of type enum
switch(d){
case north:
country = "P";
break;
case south:
country = "Q";
break;
case east:
country = "R";
break;
case west:
country = "S";
break;
default:
country = "";
break;
}
// switch condition of integral type
switch(c){
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
cout << "Vowel";
break;
default:
cout << "Not a Vowel";
break;
}
UD u;
// switch condition of user defined type (conversion to integral type)
switch(u){
case 0:
case 1:
cout << "Good";
break;
default:
cout << "Not so good";
break;
}
}
Here is a fairly typical use case. You have a list of values (the enum) and a switch which checks the input to determine which you are dealing with. This assumes of course that the action you will take depends on the underlying value of the enum.
enum ImageFormat
{
FormatRGB888,
FormatRGB8888,
FormatRGB101010,
FormatRGB161616,
FormatRGB16161616
};
void SomeFunc(ImageFormat format)
{
switch(format)
{
case FormatRGB888:
// do stuff
break;
case FormatRGB8888:
// do stuff
break;
case FormatRGB101010,
// do stuff
break;
case FormatRGB161616:
// do stuff
break;
case FormatRGB16161616:
// do stuff
break;
default:
// bad value for 'format'
}
}
Say you have an enum
enum expr_type {
EXPR_TYPE_ADD,
EXPR_TYPE_SUBTRACT,
EXPR_TYPE_GET_VALUE
};
We can do a switch on this:
enum expr_type t = /* get input somehow and find the type */;
switch(t) {
case EXPR_TYPE_ADD:
cout << "Operator Add";
/* fall through */
case EXPR_TYPE_SUBTRACT:
cout << "Operator (Add or Subtract)";
break;
case EXPR_TYPE_GET_VALUE;
cout << "Getting some value";
break;
}
You have to put in the break; so it doesn't fallthrough - Currently, EXPR_TYPE_ADD will exute all the code for EXPR_TYPE_SUBTRACT. Make sure to use break correctly!
Switch statements are a more efficient way of doing a lot of ifs and elses.
import java.util.Scanner;
class Date{
public static void main(String[] args) {
String dow;
String wowby;
String yowby;
Double n1,n2,res;
Scanner scan = new Scanner (System.in);
System.out.print("Enter Date (dd/mm/yy): ");
String date = scan.nextLine();
String dd = date.substring(0,2);
String mm = date.substring(3,5);
String yy = date.substring(6,8);
int d = Integer.valueOf(dd);
int m = Integer.valueOf(mm);
int y = Integer.valueOf(yy);
boolean valid = (d>=1) && (d<31)||(m>=1) && (m<12);//||((y>=00) && (y<99));
if(!valid)
System.out.print("Invalid date");
else {
switch (dd)
{
case "01":
System.out.print("First of ");
switch (mm) {
case "01":
System.out.print("January,2020");
break;
case "02":
System.out.print("February,2020");
break;
case "03":
System.out.print("March,2020");
break;
case "04":
System.out.print("April,2020");
break;
case "05":
System.out.print("May,2020");
break;
case "06":
System.out.print("June,2020");
break;
case "07":
System.out.print("July,2020");
break;
case "08":
System.out.print("August,2020");
break;
case "09":
System.out.print("September,2020");
break;
case "10":
System.out.print("October,2020");
break;
case "11":
System.out.print("November,2020");
break;
case "12":
System.out.print("December,2020");
break;
default:
System.out.print(" Invalid date ");
}
break;
case "02":
System.out.print("Second of ");
switch (mm)
{
case "01":
System.out.print("January,2020");
break;
case "02":
System.out.print("February,2020");
break;
case "03":
System.out.print("March,2020");
break;
case "04":
System.out.print("April,2020");
break;
case "05":
System.out.print("May,2020");
break;
case "06":
System.out.print("June,2020");
break;
case "07":
System.out.print("July,2020");
break;
case "08":
System.out.print("August,2020");
break;
case "09":
System.out.print("September,2020");
break;
case "10":
System.out.print("October,2020");
break;
case "11":
System.out.print("November,2020");
break;
case "12":
System.out.print("December,2020");
break;
default:
System.out.print(" Invalid month ");
}
break;
case "03":
System.out.print("Third of ");
switch (mm)
{
case "01":
System.out.print("January,2020");
break;
case "02":
System.out.print("February,2020");
break;
case "03":
System.out.print("March,2020");
break;
case "04":
System.out.print("April,2020");
break;
case "05":
System.out.print("May,2020");
break;
case "06":
System.out.print("June,2020");
break;
case "07":
System.out.print("July,2020");
break;
case "08":
System.out.print("August,2020");
break;
case "09":
System.out.print("September,2020");
break;
case "10":
System.out.print("October,2020");
break;
case "11":
System.out.print("November,2020");
break;
case "12":
System.out.print("December,2020");
break;
default:
System.out.print(" Invalid month ");
}
return;
}
}
}
}