void useproxynum ( ) { bUseProxy = true; return; };
void useacctnum ( ) { bUseProxy = false; return; };
Can anyone give me some insight into what these c++ statements are doing? There are in a header file.
bUseProxy is defined above
bool bUseProxy;
I'm trying to figure out what useproxynum is (method call?) and I'm also trying to figure out how to find the code behind it.
This is in Visual Studio 6.
They are inline method definitions. The return statements are extremely unnecessary.
If it were me, i'd replace that with this:
void useNum(bool proxy) { bUseProxy = proxy; }
Those are not statements. Those are 2 methods (seems to be inline). One of them just sets true to bUseProxy variable the other sets false. Thats it.
They are both methods. The lines between the { } are the code. These are inlined methods and don't have a separate implementation in a .cpp file.
You can call useproxynum() in your code, and it will cause the bUseProxy value to be set to true.
Or, you can call useacctnum() in your code and it will cause bUseProxy to be false.
This bUseProxy is probably used somewhere else.
void doSomething(int id) {
if(bUseProxy) {
lookupWithProxy(id);
}
else {
lookupWithAccNum(id);
}
}
It's worth noting that the return; statements are kind of silly - reaching the end of the function block will cause the function to return all by itself.
"Trying to figure out the code behind it" ... no no, the code is in front of it =)
they are inline methods.
when called, they set the value of the boolean, then return.
Related
I have code that does something like this:
//datareader.cpp
if (populateFoo(dataReader, foo))
else {
// Do other things with the reader.
}
//foo.cpp
bool populateFoo(const DataReader &dataReader, Foo &foo)
{
if (dataReader.name() == "bar") {
foo.bar() = dataReader.value();
return true;
} // More similar checks.
return false;
}
I feel like it's misleading to have an if statement with conditions that have side-effects. However, I can't move the body of the populateFoo function into datareader.cpp. Is there a good way to restructure this code so we get rid of this misleading if statement, without duplicating the body of populateFoo()?
Do you have a strong hatred of local variables? If not:
bool populated = populateFoo(dataReader, foo);
if (populated)
{
// Do things
}
else
{
// Do other things
}
The compiler will almost certainly emit exactly the same code, so performance shouldn't be an issue. It's a readability/style choice, ultimately.
The obvious solution seems like storing the result of populateFoo and using it for determining whether populateFoo was successful:
bool fooPopulated = populateFoo(dataReader, Foo);
if (!fooPopulated)
//Do other things with reader.
However, I don't find the original difficult to understand, and it's a fairly well-established practice to both modify values and test the success of the modification in the same line. However, I would change it to:
if (!populateFoo(dataReader, Foo)
//Do other things with reader.
How about:
if (!populateFoo(dataReader, foo)) {
// Do other things with the reader.
}
Edit: The title of the question suggests it is the fact the if statement is empty that bothers you but the body seems more that it is the side effect that is the concern. I think it's fine in C++ to have conditions in if statements that have side effects but this won't solve your issue if you want to avoid that.
Having conditions with side-effects is quite common - think about calling a C API and checking its return code for errors.
Usually, as long as it's not buried in a complicated expression where it may be missed by the casual bystander, I don't bother to do particular refactorings, but, in case you wanted to make it extra clear (or document what the return value is, which is particularly useful in case of booleans) just assign it to a variable before the branch - or even just a few comments may help.
You could split the populateFoo function into two, a const check function (shouldPopulateFoo) that checks the condition, and another non-const function that performs the actual modifications (populateFoo):
//datareader.cpp
if (shouldPopulateFoo(dataReader)) {
populateFoo(dataReader, foo);
}
else {
// Do other things with the reader.
}
//foo.cpp
bool shouldPopulateFoo(const DataReader &dataReader) /* const */
{
return (dataReader.name() == "bar");
}
void populateFoo(const DataReader &dataReader, Foo &foo) /* non-const */
{
assert(shouldPopulateFoo(dataReader));
foo.bar = dataReader.value();
}
Note that when using these functions as class methods, you could declare the check function const.
How about:
if (populateFoo(dataReader, foo) == false) {
// Do other things with the reader.
}
It is very readable, I often see code where the returned value from function is a signal to the caller for branching in the caller. The else block with empty if block bothers me more then the side effects inside the if (). There is a sense of reverse logic, which is alway less readable.
E.g. a class Unit has three functions:
class Unit{
void StandUp();
void SitDown();
void Die();
}
I have a list of pointers list<Unit*> UnitList;
When I want everyone to stand up:
void EveryoneStandUp(){
for(list<Unit*> it = UnitList.begin(); it != UnitList.eng(); it++){
(*it)->StandUp();
}
}
Now if I want everyone to SitDown, I would copy the code above and change StandUp() to SitDown(). For every new function I write, if I want everyone to do it, I have to have another for-loop body in my code.
Is it possible to put this for-loop body in another function, which I can reuse whenever I want to call a certain function from all of the members in the UnitList?
I feel like this must have answers somewhere else, I tried googling but have little idea which keywords I should look for. Thanks for answers!
You may do:
void Everyone(void (Unit::*method)())
{
for (std::list<Unit*>::iterator it = UnitList.begin(); it != UnitList.end(); it++){
((*it)->*method)();
}
}
And call it
Everyone(&Unit::StandUp);
but in c++11, your example may be rewritten as:
for (auto* unit : UnitList) {
unit->StandUp();
}
which seems clear enough.
you can use c++ algorithms available,
http://www.cplusplus.com/reference/algorithm/for_each/
It can be solved by having a helper function, which does the actual looping and have the member function to be called as an argument.
Something like this:
void UnitHelperFunction(void (Unit::*func)())
{
for (...)
{
((*itr)->*func)();
}
}
void EveryoneStandUp()
{
UnitHelperFunction(&Unit::StandUp);
}
Alright, I have been having this problem for a while and I believe I have pin-pointed where the problem is, but I am not sure how to fix it.
void Unit::AddStatusEffect(StatusEffect effect)
{
// Add status effect and if it effects what actions a unit can do, do it here.
myEffects.push_back(effect);
if( effect.GetEffect == effect.STUN)
{
myCanMove = false;
myCanAttack = false;
myCanCast = false;
}
else if (effect.GetEffect == effect.MUTE)
{
myCanCast = false;
}
else if (effect.GetEffect == effect.BLIND)
{
myCanHit = false;
}
else
{}
}
My problem seems to be with the effect.GetEffect return function within the StatusEffect class. If I ask if(effect.STUN == effect.STUN) I get no errors which is why I believe the function is the problem. The error I get seems to be:
function call missing argument list; use '&StatusEffect::GetEffect' to create a pointer to member
(Here is the class in case there is something in there that may be the problem)
class StatusEffect
{
public:
enum Effect { POISON, BURN, BLEED, FREEZE, MUTE, STUN, BLIND, ATKBOOST, HPREGEN, MANAREGEN, MATKBOOST, DEFENSEBOOST, MAGICDEFENSEBOOST };
private:
Effect myEffect;
public:
////////////////////////////////////////////////////////////////
// Data Retrievers
////////////////////////////////////////////////////////////////
Effect const GetEffect() { return myEffect; }
StatusEffect(void);
~StatusEffect(void);
};
I hope I explained my problem well enough. Everything I read up on didn't seem to help me solve this problem.
In Unit::AddStatusEffect, replace effect.GetEffect by effect.GetEffect()
The difference between effect.GetEffect and effect.GetEffect() is that the first evaluates to a pointer to a member function (the function does not get called) while the second evaluates to the returned value of the function call.
You have to call a method or function by adding parentheses, even if there is no argument.
effect.GetEffect()
Let's say you have a function in C/C++, that behaves a certain way the first time it runs. And then, all other times it behaves another way (see below for example). After it runs the first time, the if statement becomes redundant and could be optimized away if speed is important. Is there any way to make this optimization?
bool val = true;
void function1() {
if (val == true) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
gcc has a builtin function that let you inform the implementation about branch prediction:
__builtin_expect
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
For example in your case:
bool val = true;
void function1()
{
if (__builtin_expect(val, 0)) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
You should only make the change if you're certain that it truly is a bottleneck. With branch-prediction, the if statement is probably instant, since it's a very predictable pattern.
That said, you can use callbacks:
#include <iostream>
using namespace std;
typedef void (*FunPtr) (void);
FunPtr method;
void subsequentRun()
{
std::cout << "subsequent call" << std::endl;
}
void firstRun()
{
std::cout << "first run" << std::endl;
method = subsequentRun;
}
int main()
{
method = firstRun;
method();
method();
method();
}
produces the output:
first run subsequent call subsequent call
You could use a function pointer but then it will require an indirect call in any case:
void (*yourFunction)(void) = &firstCall;
void firstCall() {
..
yourFunction = &otherCalls;
}
void otherCalls() {
..
}
void main()
{
yourFunction();
}
One possible method is to compile two different versions of the function (this can be done from a single function in the source with templates), and use a function pointer or object to decide at runtime. However, the pointer overhead will likely outweigh any potential gains unless your function is really expensive.
You could use a static member variable instead of a global variable..
Or, if the code you're running the first time changes something for all future uses (eg, opening a file?), you could use that change as a check to determine whether or not to run the code (ie, check if the file is open). This would save you the extra variable. Also, it might help with error checking - if for some reason the initial change is be unchanged by another operation (eg, the file is on removable media that is removed improperly), your check could try to re-do the change.
A compiler can only optimize what is known at compile time.
In your case, the value of val is only known at runtime, so it can't be optimized.
The if test is very quick, you shouldn't worry about optimizing it.
If you'd like to make the code a little bit cleaner you could make the variable local to the function using static:
void function() {
static bool firstRun = true;
if (firstRun) {
firstRun = false;
...
}
else {
...
}
}
On entering the function for the first time, firstRun would be true, and it would persist so each time the function is called, the firstRun variable will be the same instance as the ones before it (and will be false each subsequent time).
This could be used well with #ouah's solution.
Compilers like g++ (and I'm sure msvc) support generating profile data upon a first run, then using that data to better guess what branches are most likely to be followed, and optimizing accordingly. If you're using gcc, look at the -fprofile-generate option.
The expected behavior is that the compiler will optimize that if statement such that the else will be ordered first, thus avoiding the jmp operation on all your subsequent calls, making it pretty much as fast as if it wern't there, especially if you return somewhere in that else (thus avoiding having to jump past the 'if' statements)
One way to make this optimization is to split the function in two. Instead of:
void function1()
{
if (val == true) {
// do something
val = false;
} else {
// do other stuff
}
}
Do this:
void function1()
{
// do something
}
void function2()
{
// do other stuff
}
One thing you can do is put the logic into the constructor of an object, which is then defined static. If such a static object occurs in a block scope, the constructor is run the fist time that an execution of that scope takes place. The once-only check is emitted by the compiler.
You can also put static objects at file scope, and then they are initialized before main is called.
I'm giving this answer because perhaps you're not making effective use of C++ classes.
(Regarding C/C++, there is no such language. There is C and there is C++. Are you working in C that has to also compile as C++ (sometimes called, unofficially, "Clean C"), or are you really working in C++?)
What is "Clean C" and how does it differ from standard C?
To remain compiler INDEPENDENT you can code the parts of if() in one function and else{} in another. almost all compilers optimize the if() else{} - so, once the most LIKELY being the else{} - hence code the occasional executable code in if() and the rest in a separate function that's called in else
Say I have the following function:
Thingy& getThingy(int id)
{
for ( int i = 0; i < something(); ++i )
{
// normal execution guarantees that the Thingy we're looking for exists
if ( thingyArray[i].id == id )
return thingyArray[i];
}
// If we got this far, then something went horribly wrong and we can't recover.
// This function terminates the program.
fatalError("The sky is falling!");
// Execution will never reach this point.
}
Compilers will typically complain at this, saying that "not all control paths return a value". Which is technically true, but the control paths that don't return a value abort the program before the function ends, and are therefore semantically correct. Is there a way to tell the compiler (VS2010 in my case, but I'm curious about others as well) that a certain control path is to be ignored for the purposes of this check, without suppressing the warning completely or returning a nonsensical dummy value at the end of the function?
You can annotate the function fatalError (its declaration) to let the compiler know it will never return.
In C++11, this would be something like:
[[noreturn]] void fatalError(std::string const&);
Pre C++11, you have compiler specific attributes, such as GCC's:
void fatalError(std::string const&) __attribute__((noreturn));
or Visual Studio's:
__declspec(noreturn) void fatalError(std::string const&);
Why don't you throw an exception? That would solve the problem and it would force the calling method to deal with the exception.
If you did manage to haggle the warning out some way or other, you are still left with having to do something with the function that calls getThingy(). What happens when getThingy() fails? How will the caller know? What you have here is an exception (conceptually) and your design should reflect that.
You can use a run time assertion in lieu of your fatalError routine. This would just look like:
Thingy& getThingy(int id)
{
for ( int i = 0; i < something(); ++i )
{
if ( thingyArray[i].id == id )
return thingyArray[i];
}
// Clean up and error condition reporting go here.
assert(false);
}