Explain what this c++ bool line mean in this cpp book - c++

playpen pp;
bool more(true);
do{
display_content();
int const choice(get_choice));
more = do_choice(pp, choice);
} while (more)
function code >>
bool do_choice(int choice){
bool more(true);
switch(choice){
case 0:
clear_playpen(???);
break;
case 1:
more = false;
break;
case 2:
change_plotmode(???);
break;
case 3:
plot_pixel(???);
break;
case 4:
change_scale(???);
break;
default:
throw problem("Not a valid option");
}
return more;
}
the do_choice function has a declaration bool do_choice(int choice);
with the last line in definition as return true to the bool type. Why will the author again in the cpp script above say more = do_choice(...) which I am understanding to mean true = true // what use is that? Sounds gibberish to me

You're confusing the assignment operator (=) with the comparison operator (==).
The call to do_choice updates more so the loop will stop eventually.

Related

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;
}
}
}
}

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).

How to apply different instantiations to the same name of object?

int lim;
do{
cin>>lim;
switch(lim)
{
case 1: {mpa<1,int,const char*> C; }break;
case 2: {mpa<2,int,const char*> C; }break;
case 3: {mpa<3,int,const char*> C; }break;
case 4: {mpa<4,int,const char*> C; }break;
case 5: {mpa<5,int,const char*> C; }break;
default: cout<<"Incorrect number, please repeat\n";
}
}while(lim<1 || lim>5);
I want to pass a value(1,2,3,4 or 5) to the template int a,typename T1,typename T2. I need different instantiations of this template. But object C will be destroyed after switch. How to apply different instantiations to the same name of object?
In this case, I think the best option is to rethink class mpa to not require that first parameter at compile time. Seriously, everyone hates rewriting things, but that's what you should do.
Since I know you'll ignore that, here's a workaround:
Make a class mpa_base<class, class>, that mpa inherits from, and has all the same functions, but they're all virtual (ESPECIALLY the destructor). Then, you can do this:
typedef mpa_base<int, const char*> mpa_int_pchar;
std::unique_ptr<mpa_int_pchar> C; //this is a smart pointer to a mpa object
int lim;
do{
cin>>lim;
switch(lim)
{
case 1: C.reset(new mpa<1,int,const char*>()); break;
case 2: C.reset(new mpa<2,int,const char*>()); break;
case 3: C.reset(new mpa<3,int,const char*>()); break;
case 4: C.reset(new mpa<4,int,const char*>()); break;
case 5: C.reset(new mpa<5,int,const char*>()); break;
default: cout<<"Incorrect number, please repeat\n";
}
}while(lim<1 || lim>5);
Refactor the common part in another function and then you can easily do this. Also, always have the input from the stream as part of the loop check or make it a break-condition.
template<class MPA>
void foo(MPA const& mpa){
// whatever you want to do, do it here
}
int lim = 0;
do{
if(!(cin >> lim)){ // broken input
cin.clear(); // clear error flags
break; // bail out
}
switch(lim)
{
case 1: { foo(mpa<1, int, char const*>(/*params*/)); }break;
case 2: { foo(mpa<2, int, char const*>(/*params*/)); }break;
case 3: { foo(mpa<3, int, char const*>(/*params*/)); }break;
case 4: { foo(mpa<4, int, char const*>(/*params*/)); }break;
case 5: { foo(mpa<5, int, char const*>(/*params*/)); }break;
default: cout<<"Incorrect number, please repeat\n";
}
}while(lim < 1 || lim > 5);

C++ Stack Implementation (not working right)

Here's the previous thread where I got help with this same lab. My stack is misbehaving, to say the least, when I add an item to stack, to print out later, it doesn't seem to add right. I always print out plus'(+), not matter if I enter another operand(*,/,+).
I am using a stack to convert a, user inputed, infix express to postfix. It seems to work fine except printing out the operands in the stack at the end.
#include <iostream>;
#include <vector>
using namespace std;
class DishWell{
public:
char ReturnFront(){
return Well.front();
}
void Push(char x){
Well.push_back(x);
}
void Pop(){
Well.pop_back();
}
bool IsEmpty(){
return Well.empty();
}
private:
vector<char> Well;
};
bool Precidence(char Input, char Stack){
int InputPrecidence,StackPrecidence;
switch (Input){
case '*':
InputPrecidence = 4;
break;
case '/':
InputPrecidence = 4;
break;
case '+':
InputPrecidence = 3;
break;
case '-':
InputPrecidence = 3;
break;
case '(':
InputPrecidence = 2;
break;
default:
InputPrecidence = 0;
}
switch (Stack){
case '*':
StackPrecidence = 4;
break;
case '/':
StackPrecidence = 4;
break;
case '+':
StackPrecidence = 3;
break;
case '-':
StackPrecidence = 3;
break;
case '(':
StackPrecidence = 2;
break;
default:
StackPrecidence = 0;
}
if(InputPrecidence>StackPrecidence) return true;
else return false;
}
int main(int argc, char** argv) {
DishWell DishTray;
char Input;
bool InputFlag;
InputFlag = true;
cout<<"Enter Input, invalid input will terminate"<<endl;
while(InputFlag){
cout<<"Input: ";
cin>>Input;
cout<<endl;
if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||Input>='0'&&Input<='9')))//If Digit or Number
cout<<Input;
if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand
if(DishTray.IsEmpty())
DishTray.Push(Input);
else if(Precidence(Input,DishTray.ReturnFront()))
DishTray.Push(Input);
else if(!Precidence(Input,DishTray.ReturnFront()))
cout<<"Output: "<<Input<<endl;
}
else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||(Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand
InputFlag = false;
}
int counter = 0;
while(!DishTray.IsEmpty()){
counter++;
cout<<counter<<" Element "<<DishTray.ReturnFront()<<endl;
DishTray.Pop();
}
return 0;
Thank you, Macaire Bell
Your loop calls front(), but then calls pop_back(). This will always return the first element in the vector, until all elements are popped, since you are never erasing the front element. Your ReturnFront() method should probably be:
char ReturnBack(){
return Well.back();
}
And then your loop at the end:
while(!DishTray.IsEmpty()){
counter++;
cout<<counter<<" Element "<<DishTray.ReturnBack()<<endl; // will return last element
DishTray.Pop(); // actually pop the element printed
}
When you're working with a stack, you usually want to be able to see the value on the top of the stack. Your class only allows the very first item pushed (i.e. the bottom of the stack) to be visible. Your ReturnFront() should probably return Well.back() and perhaps it should be called something like ReturnTop().
Wouldn't you want to see the value returned from pop_back() instead if discarding it as you're currently doing?

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;
}
}
}
}