How to pass a bool variable by reference in a non-bool function? - c++

I looked at how to pass a bool by reference, but that function returned the bool inside of it. I also looked here on stack overflow, but the suggestions made by the commenters did not improve my situation. So,
I have a function:
myTreeNode* search_tree(myTreeNode *test_irater, char p_test, bool &flag)
That obviously returns a myTreeNode* type. I also have a variable, bool flag that I want to change the value of within the function. However, when I try to pass the bool by reference, I get an error message of
error: invalid initialization of non-const reference of type 'bool&'
from an rvalue of type 'bool*'|
How do I go about passing a bool by reference without returning a bool? I am running on the latest version of CodeBlocks, if that is relevant.
Edit: code
myTreeNode* search_tree(myTreeNode *test_irater, char p_test, bool &flag)
{
switch(p_test)
{
case 'a':
if (test_irater->childA == NULL)
flag = false;
else {
test_irater = test_irater->childA;
flag = true;
}
break;
case 't':
if (test_irater->childT == NULL)
flag = false;
else {
test_irater = test_irater->childT;
flag = true;
}
break;
case 'c':
if (test_irater->childC == NULL)
flag = false;
else {
test_irater = test_irater->childC;
flag = true;
}
break;
case 'g':
if (test_irater->childG == NULL)
flag = false;
else {
test_irater = test_irater->childG;
flag = true;
}
break;
}
return test_irater;
}
called like:
test_irater = search_tree(test_irater, p_test, &flag);

You are using the addressof(&) operator, meaning &flag is converted to bool*
Remove it, and it should work:
test_irater = search_tree(test_irater, p_test, flag);

Related

Pointer to member function of instance instead of class

I have the following class when I get a pointer to a member function according to some condition and then call the function.
class Test
{
public:
bool isChar(char ch) { return (ch >= 'a' && ch <= 'z'); }
bool isNumeric(char ch) { return (ch >= '0' && ch <= '0'); }
enum class TestType
{
Undefined,
Char,
Numeric,
AnotherOne,
};
bool TestFor(TestType type, char ch)
{
typedef bool (Test::*fptr)(char);
fptr f = nullptr;
switch(type)
{
case TestType::Char:
f = &Test::isChar;
break;
case TestType::Numeric:
f = &Test::isNumeric;
break;
default: break;
}
if(f != nullptr)
{
return (this->*f)(ch);
}
return false;
}
};
But actually I don't like the syntax. Is there a way to replace
(this->*f)(ch)
with
f(ch)
?
In my real code the function a big enough and it's not so clear what (this->*f) is. I'm looking for some c++11 solution. I know about std::function and I will use it if if no solution will be found.
Update
The solution that I decided to use, if suddenly someone needs it: (thanks for #StoryTeller - Unslander Monica)
bool TestFor(TestType type, char ch)
{
bool(Test::* fptr)(char) = nullptr;
switch(type)
{
case TestType::Char:
fptr = &Test::isChar;
break;
case TestType::Numeric:
fptr = &Test::isNumeric;
break;
default: break;
}
if(fptr != nullptr)
{
auto caller = std::mem_fn(fptr);
return caller(this, ch);
}
return false;
}
If the syntax bothers you so much, you can always use std::mem_fn to generate a cheap one-time wrapper around a member function.
auto caller = std::mem_fn(f);
caller(this, ch);

How to fix this statement may fall through [-Werror=implicit-fallthrough=]?

What does
this statement may fall through [-Werror=implicit-fallthrough=]
mean ?
I getting this error while compiling at statement like this:
switch(eT)
{
case SEL_CRIT:
{
TYPE1* psSel;
iRetVal = dbseq(enB->m_ps,
NULL, NULL, &esM, NULL, ESEC);
while (iRetVal == 0)
{
if(psEnterprise)
{
bool iFound = false;
for (i = 0; i< psME->m_pslave[0].m_uc; i++)
{
ENT node1;
sEOS = psME>m_pslave[0].m_pslavecnt[i];
}
if (iFound && (psME->m_NOTOVERLOADED == false))
{
return psME;
}
}
}
psSel = (M_EN*)pCrit;
LOG_INFO(FAIL_TO_LOAD, psME->m_ONG, psME->EN);
int_Enterprise = NULL;
}
at
int_Enterprise = NULL;
where
int_Enterprise is some structure pointer.
How can I fix this?
You have no break; at the end of your case: so execution will fall through into the next case. Add a break statement to prevent fall-through if that's what you want or add a [[fallthrough]] attribute if fallthrough is intended.

How to check if bool method returns value in an if statement C++

I'm having a go at creating classes and have created this method inside
Input.cpp:
bool Input::CheckKeyPress(char key)
{
SDL_Event ev;
while (SDL_PollEvent(&ev))
{
keyState = SDL_GetKeyboardState(NULL);
if (ev.type == SDL_KEYDOWN)
{
switch (key)
{
case 'w' :
if (keyState[SDL_SCANCODE_W])
{
return 1;
}
else
{
return 0;
}
case 'a' :
if (keyState[SDL_SCANCODE_A])
{
return 1;
}
else
{
return 0;
}
case 's' :
if (keyState[SDL_SCANCODE_S])
{
return 1;
}
else
{
return 0;
}
case 'd' :
if (keyState[SDL_SCANCODE_D])
{
return 1;
}
else
{
return 0;
}
}
}
}
}
I try to use it in an if-statement in my main class like so:
if (bool Input::CheckKeyPress(w))
{
//do stuff
}
However as expected I get an error saying: "A function type is not allowed here" So what do I do?
Just write:
if (CheckKeyPress(w))
{
//do stuff
}
You have already told the compiler that the CheckKeyPress() method returns a bool. Here, you are just calling the function, so you don't need to mention the return type again. When the control will call the function CheckKeyPress(), it will return a bool value that would be checked for its truth within the if statement.
Note: There are two possibilities:
Instance is a different class:
If Instance is altogether a different class and CheckKeyPress() is
one of the methods that it contains, then you first need to create an object of the Instance class like below:
Instance it = new Instance(); //or just Instance it;
and then access the function via:
it.CheckKeyPress();
If the method is static:
In this case you need to call the method as:
Input::CheckKeyPress(w)
without just the return type (bool).
Hope this is helpful. Thank you for your inputs, #user4581301.

C++ returning bool is always false?

I implemented a Quiz Code and did a short change at the end of it to check if the User answered it correctly.
My if / else looks like this:
if (answer == rightanswer){
rightA = true;
}
else {
rightA = false;
}
return rightA;
I already checked with the debugger that if the correct answer is entered it goes to rightA = true; and to return, so this works finde.
But if i check the value of rightA it's false.
If it's needed, here is the function that i use to call the Quiz:
void gameOver(char field[HEIGHT][WIDTH], char newField[HEIGHT][WIDTH]){ // TODO
bool rightA = false;
showQuizDialog(rightA);
do{
system("cmd /c cls");
switch (rightA){
case true : cout << "menu"; menu(field, newField); break;
case false : showQuizDialog(rightA); break;
default : cout << " ";
}
}while(rightA == false);
}
I'm a bit hintless. I may have some logic failure in it i just don't see at the moment.
Greetings
E: I don't wanted to bomb you guys with code. But here is it:
bool showQuizDialog(bool rightA){
Quiz* quiz = Quiz::getInstance();
quiz -> askQuestion(rightA);
return rightA;
}
And the full askQuestion:
bool Quiz::askQuestion(bool rightA) {
int fragenID = rand() % this->fragen.size(); //zufällige Fragen auswählen
struct Question frage = this->fragen.at(fragenID);
std::cout << frage.frage.c_str() << std::endl << endl; //Frage stellen
int rightanswer = this->listAnswers(frage.antworten);
int answer = this->readAnswer(0, frage.antworten.size() - 1);
if (answer == rightanswer){
rightA = true;
}
else {
rightA = false;
}
return rightA;
}
Is showQuizDialog(rightA) supposed to magically change the value of rightA? (I'm assuming you're not passing it by reference).
Did you mean to write rightA = showQuizDialog(rightA) or rightA = quiz -> askQuestion(rightA)?
Also, in your switch that switches on a bool, do you expect any other values than a true or a false?
Your showQuizDIalog is a call-by-value function. So always store the return value of the function into rightA, when calling showQuizDialog, that is :
rightA = showQuizDialog(rightA);
Otherwise, change your function declaration to allow pass-by-reference, maybe like this
showQuizDialog(&rightA);
and no need to return anything from the function(just use a pointer instead of a variable rightA inside the function)

Easiest way to flip a boolean value?

I just want to flip a boolean based on what it already is. If it's true - make it false. If it's false - make it true.
Here is my code excerpt:
switch(wParam) {
case VK_F11:
if (flipVal == true) {
flipVal = false;
} else {
flipVal = true;
}
break;
case VK_F12:
if (otherVal == true) {
otherValVal = false;
} else {
otherVal = true;
}
break;
default:
break;
}
You can flip a value like so:
myVal = !myVal;
so your code would shorten down to:
switch(wParam) {
case VK_F11:
flipVal = !flipVal;
break;
case VK_F12:
otherVal = !otherVal;
break;
default:
break;
}
Clearly you need a factory pattern!
KeyFactory keyFactory = new KeyFactory();
KeyObj keyObj = keyFactory.getKeyObj(wParam);
keyObj.doStuff();
class VK_F11 extends KeyObj {
boolean val;
public void doStuff() {
val = !val;
}
}
class VK_F12 extends KeyObj {
boolean val;
public void doStuff() {
val = !val;
}
}
class KeyFactory {
public KeyObj getKeyObj(int param) {
switch(param) {
case VK_F11:
return new VK_F11();
case VK_F12:
return new VK_F12();
}
throw new KeyNotFoundException("Key " + param + " was not found!");
}
}
:D
</sarcasm>
Easiest solution that I found:
x ^= true;
If you know the values are 0 or 1, you could do flipval ^= 1.
Just for information - if instead of an integer your required field is a single bit within a larger type, use the 'xor' operator instead:
int flags;
int flag_a = 0x01;
int flag_b = 0x02;
int flag_c = 0x04;
/* I want to flip 'flag_b' without touching 'flag_a' or 'flag_c' */
flags ^= flag_b;
/* I want to set 'flag_b' */
flags |= flag_b;
/* I want to clear (or 'reset') 'flag_b' */
flags &= ~flag_b;
/* I want to test 'flag_b' */
bool b_is_set = (flags & flag_b) != 0;
Just because my favorite odd ball way to toggle a bool is not listed...
bool x = true;
x = x == false;
works too. :)
(yes the x = !x; is clearer and easier to read)
This seems to be a free-for-all ... Heh. Here's another varation, which I guess is more in the category "clever" than something I'd recommend for production code:
flipVal ^= (wParam == VK_F11);
otherVal ^= (wParam == VK_F12);
I guess it's advantages are:
Very terse
Does not require branching
And a just as obvious disadvantage is
Very terse
This is close to #korona's solution using ?: but taken one (small) step further.
The codegolf'ish solution would be more like:
flipVal = (wParam == VK_F11) ? !flipVal : flipVal;
otherVal = (wParam == VK_F12) ? !otherVal : otherVal;
flipVal ^= 1;
same goes for
otherVal
I prefer John T's solution, but if you want to go all code-golfy, your statement logically reduces to this:
//if key is down, toggle the boolean, else leave it alone.
flipVal = ((wParam==VK_F11) && !flipVal) || (!(wParam==VK_F11) && flipVal);
if(wParam==VK_F11) Break;
//if key is down, toggle the boolean, else leave it alone.
otherVal = ((wParam==VK_F12) && !otherVal) || (!(wParam==VK_F12) && otherVal);
if(wParam==VK_F12) Break;
Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:
template<typename T> bool Flip(const T& t);
You can then specialize this for different types that might pretend to be boolean. For example:
template<> bool Flip<bool>(const bool& b) { return !b; }
template<> bool Flip<int>(const int& i) { return !(i == 0); }
An example of using this construct:
if(Flip(false)) { printf("flipped false\n"); }
if(!Flip(true)) { printf("flipped true\n"); }
if(Flip(0)) { printf("flipped 0\n"); }
if(!Flip(1)) { printf("flipped 1\n"); }
No, I'm not serious.
For integers with values of 0 and 1 you can try:
value = abs(value - 1);
MWE in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Hello, World!\n");
int value = 0;
int i;
for (i=0; i<10; i++)
{
value = abs(value -1);
printf("%d\n", value);
}
return 0;
}
Just because I like to question code. I propose that you can also make use of the ternary by doing something like this:
Example:
bool flipValue = false;
bool bShouldFlip = true;
flipValue = bShouldFlip ? !flipValue : flipValue;