I make a function call and when it returns false, I continue to check indefinitely until it returns true. Is the following code is fine?
while(true)
{
bool result = func();
if(result == false)
continue;
else
break;
}
How about getting rid of the break and continue. It is not considered very nice to use them (especially when not required):
bool result;
do
{
result = func();
if(result == false) {
// Supposedly you want to do something here...?
}
} while(result == false);
Of course you can use ! instead of false to save some bytes in your source code. But I suppose that does not really matter at this point.
You could do that, but why not just:
while(!func())
{
// do what you want to do...
}
Why not use
while (!func());
instead? Some folk don't like to see an empty while and may therefore prefer #dwxw's solution.
You can make it shorter.
do
{
} while (!func());
Related
I have a condition like the following where I just want to have the second bool be the trigger for a single time, since this condition is invoked relatively often I don't like the idea of doing the assignment of it being false every time the condition is true so, I tried to take advantage of the order of logical AND and OR and the post increment operator. But it appears to work don't do what I expected it to do. So is there a way to make a post state switch for this line?
where firstTitleNotSet is:
bool firstTitleNotSet;
if (titleChangedSinceLastGet() || (p_firstTitleNotSet && p_firstTitleNotSet++))
The idea is that the first part is the primary trigger and the second is the trigger that only has to trigger the first time.
While I easily could do
if (titleChangedSinceLastGet() || p_firstTitleNotSet)
{
firstTitleNotSet = false;
//...
}
I don't like this as it is reassigning false when ever the conditional block is invoked.
So is there some way of "post change" the value of a bool from true to false? I know that this would work the other way around but this would negate the advantage of the method most time being the true trigger and therefor skipping the following check.
Note: The reasons for me making such considerations isntead of just taking the second case is, that this block will be called frequently so I'm looking to optimize its consumed runtime.
Well, you could do something like:
if (titleChangedSinceLastGet() ||
(p_firstTitleNotSet ? ((p_firstTitleNotSet=false), true):false))
An alternative syntax would be:
if (titleChangedSinceLastGet() ||
(p_firstTitleNotSet && ((p_firstTitleNotSet=false), true)))
Either one looks somewhat ugly. Note, however, that this is NOT the same as your other alternative:
if (titleChangedSinceLastGet() || p_firstTitleNotSet)
{
p_firstTitleNotSet = false;
//...
}
With your proposed alternative, pontificate the fact that p_firstTitleNotSet gets reset to false no matter what, even if the conditional was entered because titleChangedSinceLastGet().
A more readable way than the assignment inside a ternary operator inside an or inside an if would be just moving the operations to their own statements:
bool needsUpdate = titleChangedSinceLastGet();
if(!needsUpdate && firstTitleSet)
{
needsUpdate = true;
firstTitleSet = false;
}
if(needsUpdate)
{
//...
}
This is likely to produce very similar assembly than the less readable alternative proposed since ternary operators are mostly just syntactic sugar around if statements.
To demonstrate this I gave GCC Explorer the following code:
extern bool first;
bool changed();
int f1()
{
if (changed() ||
(first ? ((first=false), true):false))
return 1;
return 0;
}
int f2()
{
bool b = changed();
if(!b && first)
{
b = true;
first = false;
}
return b;
}
and the generated assembly had only small differences in the generated assembly after optimizations. Certainly have a look for yourself.
I maintain, however, that this is highly unlikely to make a noticeable difference in performance and that this is more for interest's sake.
In my opinion:
if(titleChangedSinceLastUpdate() || firstTitleSet)
{
firstTitleSet = false;
//...
}
is an (at least) equally good option.
You can compare the assembly of the above functions with this one to compare further.
bool f3()
{
if(changed() || first)
{
first = false;
return true;
}
return false;
}
In this kind of situation, I usually write:
bool firstTitleNotSet = true;
if (titleChangedSinceLastGet() || firstTitleNotSet)
{
if (firstTileNotSet) firstTitleNotSet = false;
//...
}
That second comparison will likely be optimized by the compiler.
But if you have a preference for a post-increment operator:
int iterationCount = 0;
if (titleChangedSinceLastGet() || iterationCount++ != 0)
{
//...
}
Note that this will be a problem if iterationCount overflows, but the same is true of the bool firstTitleNotSet that you were post-incrementing.
In terms of code readability and maintainability, I would recommend the former. If the logic of your code is sound, you can probably rely on the compiler to do a very good job optimizing it, even if it looks inelegant to you.
That should work:
int firstTitleSet = 0;
if (titleChangedSinceLastGet() || (!firstTitleSet++))
If you wish to avoid overflow you can do:
int b = 1;
if (titleChangedSinceLastGet() || (b=b*2%4))
at the first iteration b=2 while b=0 at the rest of them.
I do a lot of null checking in my code, and usually I will check for not null before going on to my for or more if/else statements.
For example:
if(x!=null) {
for(int y:x) {
if(y.property1 != null) {
if( y.property < n) {
}
} else {
}
}
}
Is the following better practice?
if(x ==null) {
//exit or w/e you want to do
}
for(int y:x) {
if(y ==null){
}
if(y<0) {
}
}
No, they are the same to the engine, doesn't make any difference to the engine. It depends on your logic, but here, it's the same, dude
It doesn't make any difference... Equal / Negate Equal execute same instruction cycle.
But its always a good practice to check for all required data before manipulating any calculation
These achieve the same end. It would be up to your personal preference.
if (dog.equalsIgnoreCase("yes")) {
drink.don.setCost(8.75);
drink.don.getType();
drin.l.add(drink.don.getType());
drink.c.add((double) coke.don.getCost());
cokeprice = coke + fanta.don.getCost();
else if (dog.equalsIgnoreCase("no"))
else catch(IllegalArgumentException iae) {
System.out.println("requires yes or no");
}
}
Ignore the stupid naming conventions had to change them, incase any class mates decided to steal anything ;p
I'm trying to get my if statement to allow the user input yes and do a condition, then if "no" has been entered then nothing happens just moves onto the next statement, then anything else is illegal and the program crashes.
I don't like throwing exceptions, especially if I expect that the user might type in something that I don't want. I'd rather do something like
if (userInput.equalsIgnoreCase("Yes")) {
// do yes
}
else if (userInput.equalsIgnoreCase("No")) {
// do no
}
else {
// Sorry, invalid input
}
I don't know what language you are using, nor do I know what any of the methods you are using do, but here is an example of a similar statement in C#.
First, use a method to convert the user input to a true or false (boolean) value:
public static bool IsYes (string userInput)
{
if (userInput == "yes')
{
return true;
}
else if (userInput == "no")
{
return false;
}
else
{
throw new CustomException();
}
}
Next, you can take the result of IsYes() and use it for the if else statement:
if (IsYes(userInput))
{
// code you want to execute if "yes"
}
else
{
// code you want to execute if "no"
}
Hopefully this code will give you an idea of how to use if-else statements, but in the future please explain your question more clearely. Remember, this is C#, so although if statements are similar in almost all languages some of the other code will differ. Also, this is just an example, it won't do anything on its own.
I have this code...
void drawMap(void)
{
if (false)
return;
for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
{
if ((*iter)->get() == NULL)
continue;
PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
}
}
If I'm not mistaken it should NEVER execute...but it does...and when I change
if (false)
return;
to
if (false)
return;
else
return;
it doesn't execute at all now, but how can that first statement NOT be false? grabs headache pills
P.S. I only did this 'cause I was debugging and noticed my code was drawing to the screen when it wasn't supposed to.
if (false) will never execute its body... because the value of the condition is never true. So in the code you've given, the remainder of drawMap will always execute because it will never return at the start.
Consider if (x == 5) - that will only execute if the expression x == 5 is true. Now substitute false for x == 5...
If you want an if statement which will always execute, you want
if (true)
instead.
Count me in with the crowd that didn't actually read the problem well enough, or couldn't believe that the OP didn't understand the problem if it were so simple :)
John Skeet's answer, of course, was spot on :)
Two thoughts:
If you're in a debugger, lines can appear to be executed, out of order, not at all or at unexpected lines when compiled with optimizations. This is because some machine instructions will get 'attributed' to different source lines. Compile without optimization to eliminate the source of confusion. It is confusing only, as optimizations should (! barring compiler bugs) not alter effective behaviour
It could be that you're getting an evil #define for false that you cannot trust. Rule this out by running the code through preprocessor only. g++ -E will do that. MSVC++ has an option to 'keep preprocessed' source
Blockquote
if (false)
is analagous to
if (1 == 2)
and will therefore never execute the next statement (or block).
In your context consider the following comments I made:
void drawMap(void)
{
if (false) return; //Not gonna happen.
//The following will always happen
for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
{
if ((*iter)->get() == NULL)
continue;
PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
}
}
I have seen the usage of this if(false), in a switch / case like construction like this:
int ret = doSomeThingFunction();
if (false) {}
else if (ret < 0 ) {
}
else if (ret == 0) {
}
else if (ret > 0) {
}
I have a function definition, where i call multiple functions. Even if one of the function fails i need to go ahead and call the rest of the functions and finally return a single error saying whether any of the function call failed. The approach which i had followed was
int function foo()
{
int res, res1, res2, res3;
res1 = function1();
res2 = function2();
res3 = function3();
if (res1 == -1 || res2 == -1 || res3 == -1)
{
res = -1;
}
return res;
}
The possible another approach is
int function foo()
{
int res;
if (function1() == -1)
{
res = -1;
}
if (function2() == -1)
{
res = -1;
}
if (function3() == -1)
{
res = -1;
}
return res;
}
Which is a better approach?
Thanks in advance.
No difference at all, both will be optimized to same machine code. Preference, maintainability, and that depends on team guidelines, preferences.
First priority, make the code correct. That's more important than readability and optimization.
That means you need to consider what the function should return in the case where the functions it calls all succeed.
Many of the answers given to this question change the result returned or might return a failure indication if the 'sub-functions' all succeed. you need to take care not to do this.
Personally, I think the overall form of your first option is pretty good - it makes clear that the 3 sub-functions are called regardless of whether one or more of them fail. The one problem is that it returns an indeterminate result if all those functions succeed.
Be wary of answers that use bitwise-or to combine results - there are at least 2 potential problems:
as John Marshall pointed out in several comments, the order of evaluation is indeterminate. This means that if you simply string the function calls with bitwise-or the functions may be called in any order. This might not be a problem if there are no ordering dependencies between the functions, but usually there are - especially if you don't care about the returned value except as a s success/fail indicator (if you aren't using the return value, then the only reason to call the function is for its side effects)
If the functions can return positive, non-zero values when they succeed, then testing for failure becomes a bit trickier than just checking if the results or'ed together are non-zero.
Given these two potential problems, I think there's little reason to try to do anything much fancier than option 1 (or your second option) - just make sure you set res to a success value (0?) for the situation where none of the sub-functions fail.
What about:
int foo ()
{
bool failed = false;
failed |= (function1() != 0);
failed |= (function2() != 0);
failed |= (function3() != 0);
return failed? -1 : 0;
}
You could also collapse the three calls into a single expression and omit the failed variable altogether (at the expense of readability):
int foo ()
{
return ((function1() != 0) | (function2() !=0 ) | (function3() != 0))? -1 : 0;
}
I like the first approach when function1 function2 and function3 have the same signature because I can put them in a function pointer table and loop over the entries, which makes adding function4 alot easier.
If you can define any precise convention about return values you can simply use bitwise or:
int foo() {
if (function1() | function2() | function3())
return -1;
else
return 0;
}
I like the second approach better. If you want one-liners, you can do something like...
char success = 1;
success &= (foo() == desired_result_1);
success &= (bar() == desired_result_2);
etc.
The 2nd is a "better" approach. However, I'd go more without the needless carrying around of an indicator variable:
if( function2() == -1 ){
return -1;
}
Suggestion: (no magic numbers)
I'd also not use "magic numbers" like you've used it. Instead:
if( check_fail( function2() ) ){
return FAILED;
}
more clearly illustrated what you're thinking. Intent is easier to maintain. Magic numbers can sometimes wind up hurting you. For instance, I've known financial guys who couldn't understand why a transaction costing "$-1.00" caused their application to behave abnormally.
In the first form you're not checking the status until all 3 calls are completed. I think this signals your intent the clearest. The second form more closely resembles the more usual case, where you return early if an error is detected.
It's a subtle thing either way. You shouldn't be asking us strangers on the internet, you should be asking the rest of your team, because they're the ones who will have to live with it.
You use bitwise operators to make a 'neat' variant that doesn't need temp variables and has other fancyness too(with the more advanced operators): return func1()|func2();(this is the same as using logical or, ||). However, if you require checking a specific function in the callee, you can create a bitset: return func1() << 1 | func2(); (this assumes that they return 1 or zero)
I'd vote for the second one as well.
This question reminded me of something similar I do in one of my projects for form validation.
I pass in a reference to an empty string. With each condition I want to check, I either add a line of text to the string, or I don't. If after every test the string is still empty, then there were no errors, and I continue processing the form. Otherwise, I print the string as a message box (which describes the problems), and ask the user to fix the errors.
In this case I don't really care what the errors are, just that there are errors. Oh, and as a bonus, my validation code documents itself a bit because the errors that the user sees are right there.
Use local variable if you need to reuse the result somewhere. Else, call and compare.
int foo() {
return function1() | function2() | function3();
}
Yet another option: pass a pointer to the status variable to each function and have the function set it only if there is an error.
void function1(int *res)
{
bool error_flag = false;
// do work
if (error_flag && (res != NULL)
{
*res = ERROR;
}
}
// similar for function2, function3, ...
int foo()
{
int res = OK;
function1(&res);
function2(&res);
function3(&res);
return res;
}
Since all 3 functions always have to get called first and only then you care about the result, I would go for the first solution, because the order of the statements reflects this. Seems more clear to me. Also, I generally don't like functions that do more than just return a value (i.e. that have side effects) in if-clauses, but that's a personal preference.
This sounds like a job for the abundant Perl idiom "<try something> || die()".
int foo() {
int retVal = 0;
function1() != -1 || retval = -1;
function2() != -1 || retval = -1;
function3() != -1 || retval = -1;
// ...
return retVal;
}
I write it this way:
int foo()
{
int iReturn = 0;
int res1 = function1();
if (res1 == -1)
{
return iReturn;
}
int res2 = function2();
if (res2 == -1)
{
return iReturn;
}
int res3 = function3();
if (res3 == -1)
{
return iReturn;
}
return res;
}
As a coding rule, you should declare your variables as close to the place where it is used.
It is good to use intermediate variable like your res1, res2, res3.
But choose a good name so as you intent is clear when you get the value from the function.
And be careful, in the example you've given us, you never assigned the int res; that may be returned when success. The coding rule is to initialize your variable as soon as you can.
So you should also initialize your res1 res2 res3 immidiatbly.
Returning an uninitialized value leads to undefined behaviour.
I've seen code like this before which might be a little cleaner:
bool result = true;
result = function1() == -1 && result;
result = function2() == -1 && result;
result = function3() == -1 && result;
return result?-1:0;
Edit: forgot about short circuiting.