Change variable number of variables in a function - c++

I want to do something like this :
bool val = false;
bool val1 = false;
...
void function(&val,&val1,...)
{
val = false;
val1 = true;
val15 = false
...
}
I know how to pass a variable number of arguments to a function (va_arg) however i don't know how to do the same with references. Thank you for your help and i'm sorry for the stupid question.

Related

Calling function once

if (GetKeyState(VK_DOWN) & 0x80)
{
func();
}
It calls func() like 4 times when I press key
I want it to call only once when I press key
EDIT:
SHORT keyState;
SHORT keyState2;
SHORT keyState3;
static bool toogle1 = false;
static bool toogle2 = false;
static bool toogle3 = false;
if (keyState = GetAsyncKeyState(VK_DOWN) && !toogle1)
{
toogle1 = true;
}
else
toogle1 = !toogle1;
if (keyState2 = GetAsyncKeyState(VK_NUMPAD0) && !toogle2)
{
toogle2 = true;
}
else
toogle2 = !toogle2;
if (keyState3 = GetAsyncKeyState(VK_NUMPAD1) && !toogle3)
{
toogle3 = true;
}
else
toogle3 = !toogle3;
Here is how I did it, will it work?
static bool once = false;
if (GetKeyState(VK_DOWN) & 0x80)
{
if (!once)
{ once = true; func(); }
}
I guess you run this in a loop. Your idea with toggling a flag when called is not bad, but since you toggle it back in the else case, you call func() half as often as before (every 2nd time).
When you want to call it again (I think you want, according to your code), when the key is pressed again, but not spam the function call, you can use a variable to store which key was pressed last and only call func(), when it was another key (you can also add a "no key pressed" state.
If you really just want to call it once, just remove your else statements.

C++ Create std::list in function and return through arguments

How to correct return created std::list through function argument? Now, I try so:
bool DatabaseHandler::tags(std::list<Tag> *tags)
{
QString sql = "SELECT * FROM " + Tag::TABLE_NAME + ";";
QSqlQueryModel model;
model.setQuery(sql);
if(model.lastError().type() != QSqlError::NoError) {
log(sql);
tags = NULL;
return false;
}
const int count = model.rowCount();
if(count > 0)
tags = new std::list<Tag>(count);
else
tags = new std::list<Tag>();
//some code
return true;
}
After I can use it:
std::list<Tag> tags;
mDB->tags(&tags);
Now, I fix my function:
bool DatabaseHandler::tags(std::list<Tag> **tags)
{
QString sql = "SELECT * FROM " + Tag::TABLE_NAME + ";";
QSqlQueryModel model;
model.setQuery(sql);
if(model.lastError().type() != QSqlError::NoError) {
log(sql);
*tags = NULL;
return false;
}
const int count = model.rowCount();
if(count > 0)
*tags = new std::list<Tag>(count);
else
*tags = new std::list<Tag>();
for(int i = 0; i < count; ++i) {
auto record = model.record(i);
Tag tag(record.value(Table::KEY_ID).toInt());
(*tags)->push_back(tag);
}
return true;
}
It works but list return size 4 although loop executes only 2 iterations and empty child objects (if I just called their default constructor). The Tag class hasn't copy constructor.
Since you passed an already instantiated list as a pointer to the function, there is no need to create another list.
In that sense, you question is pretty unclear. I'd suggest you read up a bit on pointers, references and function calls in general.
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/doc/tutorial/functions/
UPDATE: I still strongly suggest you read up on the mentioned topics, since you don't know these fundamental points.
Anyway, this is what you probably want to do (event though I would suggest using references, here is the solution with pointers):
bool someFunc(std::list<Tag> **tags) {
// by default null the output argument
*tags = nullptr;
if (error) {
return false;
}
// dereference tags and assign it the address to a new instance of list<Tag>
*tags = new std::list<Tag>();
return true
}
std::list<Tag> *yourList;
if (someFunc(&yourList)) {
// then yourList is valid
} else {
// then you had an error and yourList == nullptr
}
However, this is not idiomatic C++. Please read a modern book or tutorial.
Use a reference.
bool DatabaseHandler::tags(std::list<Tag>& tags);
std::list<Tag> tags;
mDB->tags(tags);
You'll have to change all the -> to ., of course. Every operation done on the reference in the function will be done to the original tags list it was called with.
EDIT: If you want to create the list inside the function and return it, you have a couple options. The closest, I think, is to just return a list pointer, and return nullptr if the function fails.
//beware, pseudocode ahead
std::list<Tag>* DatabaseHandler::tags() //return new list
{
if (success)
return new std::list<Tag>(...); //construct with whatever
else
return nullptr; //null pointer return, didn't work
}
std::list<Tag> tags* = mDB->tags();
You could alternatively have it return an empty list instead, depending on how you want it to work. Taking a reference to a pointer would work the same way, too.
bool DatabaseHandler::tags(std::list<Tag>*&); //return true/false
std::list<Tag>* tags;
mDB->tags(tags); //tags will be set to point to a list if it worked

C++, Adding conditions in class vars

The title may not be right because I can't find an appropriate words for it.
I want to add conditions to some object (instance created by class).
In obj.h: (excluding preprocessor commands)
class obj {
public:
void addCondition( bool cond );
void useCondition();
private:
bool conditions;
};
In obj.cpp: (excluding preprocessor commands)
void obj::addCondition( bool cond )
{
//What to write here, is the question in short!!!
}
void obj::useCondition()
{
if(conditions)
{
//Do something...
}
}
Suppose that the conditions was:
conditions = value1 > value2;
I wanted to 'ADD' a condition in conditions so, that it becomes something like that:
conditions = (value1 > value2) || (value3 <= value4);
OR
conditions = (value 1 > value2) && (value3 <= value4);
If I am wrong about something in asking things, I am sorry! If you know something other than the answer but the whole different thing that does the same thing, don't hesitate to discuss it.
Thanks in advance!
I assume you know why conditions field and condition parameter are both simple boolean variables. If that is true, it could be very simple, but you should replace addCondition with andCondition and orCondition :
void obj::andCondition( bool cond )
{
conditions = conditions && condition;
}
void obj::orCondition( bool cond )
{
conditions = conditions || condition;
}
And you should define whether conditions is initialy true or false. You can always set it to a defined value, because with code above :
obj.andCondition(false);
sets conditions to false, and
obj.orCondition(true);
sets conditions to true
Edit per comments:
The above answer is based on the requirement that conditions is a simple boolean variable, and condition is a simple boolean value.
Here is one example of what could be done if you want to re-evaluate the condition.
A class and-ing (resp. or-ing) conditions represented by boolean variables evaluated at the moment where useCondition is used :
class andcond {
std::list<bool *> conditions;
public:
void addCondition(bool &condition) {
conditions.push_back(&condition);
}
bool isCondition();
};
bool andcond::isCondition() {
bool retval = true;
for (std::list<bool *>::iterator it = conditions.begin(); it != conditions.end(); it++) {
retval = retval && **it;
}
return retval;
}
int main() {
bool a=false, b=true;
andcond c;
c.addCondition(a);
c.addCondition(b);
std::cout << c.isCondition() << std::endl; // is false here
a = true;
std::cout << c.isCondition() << std::endl; // is true here
return 0;
}
Note : conditions is a list of pointers to boolean variables that can be re-evaluated
You could even be more genereral by defining a full hierarchy of condition classes implementing a bool eval() method, for example the equality or inequality between 2 variables, and combinable by and and or. But it is way too complex for a disgression on an initial answer on SO. But you can try to implement this idea and ask more precise questions here when stuck ...

boolean value not changed

I'm trying to use a boolean value to keep the state I'm in.
In my header file, I declare:
bool *modified;
In my class constructor I initialize the state at false:
bool initState = false;
modified = &initState;
I then have a button that change the state to true:
bool change = true;
modified = &change;
I also have a button to see the state:
if(!*modified){
// doing something
} else{
// do something else
}
The issue is if I actually changed the state, !*modified will still be at true. I'm at a loss to see where the problem lies. Does anyone have any ideas where it is.
You are changing the value of modified, which is a bool*, and maybe to point to stack-allocated data which will be destroyed on function return. You want to change the value which is pointed to by modified.
bool initState = false;
*modified = initState;
bool change = true;
*modified = change;
This is assuming that the modified pointer is actually allocated somewhere.
Try this.
if (!(*modified))
else
bool change = true;
*modified = change;
bool initState = false;
*modified = initState;
try this code
bool *modified;
bool initState = false;
modified = initState; false
bool change = true;
modified = change; true
if ( *modified != initState)
{
do something
}
else
{
do something
}

Making the code cleaner [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Sorry if this question is not suited for SO.
I have a C++ function that approximately looks like MyFun() given below.
From this function I am calling some(say around 30) other functions that returns a boolean variable (true means success and false means failure). If any of these functions returns false, I have to return false from MyFun() too. Also, I am not supposed to exit immediately (without calling the remaining functions) if an intermediate function call fails.
Currently I am doing this as given below, but feel like there could be a more neat/concise way to handle this. Any suggestion is appreciated.
Many Thanks.
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
I would replace each if statement with a more coincise bitwise AND assignment:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
Result &= AnotherFn1(); // Another fn that returns false on failure
Result &= AnotherFn2(); // Another fn that returns false on failure
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
Use something like a std::vector of std::function. It is a lot more maintenable.
Example: http://ideone.com/0voxRl
// List all the function you want to evaluate
std::vector<std::function<bool()>> functions = {
my_func1,
my_func2,
my_func3,
my_func4
};
// Evaluate all the function returning the number of function that did fail.
unsigned long failure =
std::count_if(functions.begin(), functions.end(),
[](const std::function<bool()>& function) { return !function(); });
If you want to stop when a function fail, you just have to use std::all_of instead of std::count_if. You dissociate the control flow from the function list and that is, in my opinion, a good thing.
You can improve this by using a map of function with name as key that will allows you to output which function failed:
std::map<std::string, std::function<bool()>> function_map;
bool MyFun() // fn that returns false on failure
{
bool Result = true;
// if need to call every function, despite of the Result of the previous
Result = AnotherFn1() && Result;
Result = AnotherFn2() && Result;
// if need to avoid calling any other function after some failure
Result = Result && AnotherFn1();
Result = Result && AnotherFn2();
return Result;
}
Instead of
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
begin to use booleans as what they are, truth values:
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
Then, all those conditions have the same code; they are basically part of one big condition:
if ( !AnotherFn1()
| !AnotherFn2()
| !AnotherFn3())
{
Result = false;
}
For your specific problem, where you want all functions be called, even if you know early you'll return false, it is important to not use the short circuiting operators && and ||. Using the eager bitwise operators | and & is really a hack, because they are bitwise and not boolean (and thus hide intent), but work in your situation iff AnotherFn? return strict bools.
You can negate what you do inside; less negations yield better code:
Result = false;
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
Result = true;
}
and then you can rid these assignments and instead return straightly:
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
return true;
}
cout << "something bad happened";
return false;
Summary
Old:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
New:
bool MyFun() // fn that returns false on failure
{
if (AnotherFn1() &
AnotherFn2() &
AnotherFn3())
{
return true;
}
cout << "Some function call failed";
return false;
}
There are more possible improvements, e.g. using exceptions instead of error codes, but don't be tempted to handle "expections" instead.
! can be used as a cleaner alternative to false
Like this:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (!Result)
{
cout << "Some function call failed";
}
return Result;
}
how about using exceptions to handle failure:a neat exemple
the main question is, are the function call interdependant or not? can some be skipped if a previous one failed? ...