Postive or negative null check in if-statement - if-statement

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.

Related

If-else loop to find solution

My code is:
#include<stdio.h>
void main(void)
{
float timeLeavingTP;
int transitNumber;
float transitTime;
printf("Please enter the time leaving TP.\n");
scanf_s("%f",&timeLeavingTP);
printf("Please enter bus number.\n");
scanf_s("%d",&transitNumber);
if(timeLeavingTP==1.00)
{
if(transitNumber==27)
{
transitTime=1.56;
}
else if(transitNumber==8);
{
transitTime=1.39;
}
}
if(timeLeavingTP==6.30)
{
if(transitNumber==27)
{
transitTime=7.32;
}
else if(transitNumber==8)
{
transitTime=7.29;
}
printf("The time reached home is %f\n",transitTime);
}
}
After debugging i got
Please enter the time leaving TP
1.00
Please enter bus number
27
Please enter to continue...
My question is How do i adjust the program to make it look like the one below instead. What kind of error did i commit?
Please enter the time leaving TP
1.00
Please enter bus number
27
The time reached home is 1.56
Thanks for the help in advance!
Hi guys after including == i still got the same for my debugging? Is there something else that i did wrong?
Part 1: = vs ==
Note that:
if(timeLeavingTP=1.00)
Does not do what you expect. It assigns timeLeavingTP with 1.00.
You probably want:
if(timeLeavingTP==1.00)
Additionally, note that this error occurs 6 times in your program.
Part 2: comparing floating point numbers
Your code might work in this case, but I'm not 100% sure if it will or not. It's often difficult to directly compare 2 floating point numbers, because of the inaccuracy of storing them (for example, 0.1 is usually not representable in floating point).
Most people solve this problem in one of a few ways:
Test a range around the number.
Convert to some fixes width format. Perhaps you could store the number as an integer, knowing that it's representation is actually 0.01 * the stored number.
In this case, you could actually just store the information as strings, and compare those.
Part 3: conditionals
To write a proper conditional, it should look like:
if (condition) {
...
} else if (condition) {
...
} else if (condition) {
...
} else {
...
}
You can certainly nest conditionals as well:
if (condition) {
if (condition) {
...
} else {
...
}
} else if (condition) {
...
}
Your code, for example, messes this up when you do:
}
else(transitNumber=8);
{
transitTime=1.39;
}
Note that the else statement does not accept a conditional after it.
Part 4: excessive semicolons
Additionally, note that after the else and if statements there are no semicolons. The semicolons only appear within the braces. So this statement:
if(timeLeavingTP=6.30);
While semantically valid, does not do what you expect. You actually want to remove that semicolon.
if(timeLeavingTP == 1.00)
{
if(transitNumber == 27)
{
transitTime=1.56;
}
else if(transitNumber == 8)
{
transitTime=1.39;
}
}
else if(timeLeavingTP == 6.30)
{
if(transitNumber == 27)
{
transitTime == 7.32;
}
if(transitNumber ==8)
{
transitTime=7.29;
}
}
printf("The time reached home is %f\n",transitTime);
}
if(transitNumber=27)
{
transitTime=1.56;
}
else(transitNumber=8);
{
transitTime=1.39; //this line is executed all the time
}
This code is completly invalid!
First, you do not compare anything... transitNumber = 27 is an assignment.
Second else(transitNumber=8); again this is an assignment and it should be else if(...). Also ; at the and means that transitTime = 1.39(inside bracket) will always happen, even if transitNumber != 8
Change
if(timeLeavingTP=1.00)
to
if(timeLeavingTP==1.00)
so that you can compare timeLeavingTP correctly.

c++ function check true condition

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());

Should conditions test for positive or negative results?

Sorry if the title is rather ambiguous, I was not sure how to word it.
Is it better to phrase a condition such that the outcome you don't want enters the if statement then you exit the function or should I test for the outcome I do want and follow the statement with my code.
Maybe some examples would help:
What I mean by testing for negative result:
if(myObject == null) {
return;
}
//do whatever with myObject
What I mean by testing for positive result:
if(myObject != null) {
//do whatever with myObject
}
Sorry, if someone can word it better than me please do.
I personally prefer the first method of checking if the object is null then immediately returning. It allows the "real code" to stay unindented, linear, and can prevent many nested if statements, which I find to be more readable.
Otherwise, both ways are valid and will have the same outcome. Choose whichever works best in your situation (which can depend on any else or else if statements).
Here's a good example:
if (object1 == null) {
return;
}
// do some stuff
if (object2 == null) {
return;
}
// do some stuff
if (object3 == null) {
return;
}
Opposed to:
if (object1 != null) {
// do some stuff
if (object2 != null) {
// do some stuff
if (object3 != null) {
// do some stuff
}
}
}
I find the first one to be much more readable.
Where there is a valid action that can be taken on satisfying a positive condition, such as logging that a result set is empty, or that a variable was not assigned to, then it is better to use positive conditions. APIs can help here, such as Apache Commons StringUtils isNotBlank(), when you are testing strings. However, sometimes the cleanest thing is to go for a negative test, for example only allowing processing to proceed where a variable is non-null.

MAgic Square function C++

This is my last function for my magic square and for some reason it's giving me an error that there is "'[int]' for array subscript" but I don't know what that means, if someone could help explain what I have to do.
bool Square::is_magic()
{
for (i = 0; i < size-1; i++)
{
if (sum_row[i] != sum_row[i+1])
return false;
if (sum_col[i] != sum_col[i+1])
return false;
}
if (sum_row[0] != sum_col[0])
return false;
if (sum_row[0] != sum_maindiag[0])
return false;
if (sum_row[0] != sum_other[0])
return false;
return true;
}
Ok everybody was beginer at some time. I really recommend you to read one or two books focused on c++. (Personally I learned programming with "Learn c++ in 21 days", many complain but it was good start for me).
And for the code. Not sure that it's what you need, it should go like this:
bool Square::is_magic()
{
int i;
for (i = 0; i < size-1; i++)
{
if (sum_row[i] != sum_row[i+1])
return false;
if (sum_col[i] != sum_col[i+1])
return false;
}
if (sum_row[0] != sum_col[0])
return false;
if (sum_row[0] != sum_maindiag[0])
return false;
if (sum_row[0] != sum_other[0])
return false;
return true;
}
Some comments:
You don't need brackets for 1 command after if,for,while statement
Suggest using if -> else if -> else. Here it doesn't matter because you jump out of function as soon as you find something not correct, but in case you would continue in code you would check other statements even if it wasn't necessary.
Get used to some style, make your own or copy someone's. Personally I use brackets this way:
if (something != somethingElse){
doSomeNastyThings();
doEvenMore();
}
Good luck..
Edit: added variable declaration int for statement, updated brackets (clever idea as last 3 if-s aren't using index)
If statements are formatted like this:
if (condition) {
do_this()
}
not like this:
{
if (condition)
do_this()
}
They way you're formatting your code you're closing your for loop after two lines, which I imagine is not what you're trying to do (since you're referring to var i afterwards).

Can you rewrite this snippet without goto

Guys, I have the following code that is inside a big while loop that iterates over a tree. This is as fast as I can get this routine but I have to use a goto. I am not fundamentally against goto but if I can avoid them I would like to. (I am not trying to start a flame war, please.)
The constraints:
The current=current->child() is expensive (it's a shared_ptr) so I'd like to minimize the use of that operation at all cost.
After the operation current should be the last child it found.
cnt must count each child it encounters.
cnt++ will be replaced by some other operation (or several operations) and should only appear once :)
the code:
insideloopy:
cnt++;
if ( current->hasChild() )
{
current = current->child();
goto insideloopy;
}
Edit: Sorry guys, originally forgot to mention cnt++ should only appear once. It will be some kind of operation on the node, and should thus only be there one time. I'm also trying to avoid making that another function call.
Original answer
Assuming this is C or C++:
while (cnt++, current->hasChild())
{
current = current->child();
}
I'm not a big fan of the comma operator usually, but I don't like repeating myself either :)
Updated 'fun' answer
After learning that cnt++ is actually some multiline operation, this particular syntax would be less than ideal. Something more along the lines of your accepted answer would be better.
If you want to be really funky, this would also work:
do
{
cnt++;
} while (current->hasChild() && (current = current->child()));
Now I feel really dirty though, with my abusing the short circuiting on the && operator :)
Sane answer
Exercises in compactness aside and striving for readable code, I'm forced to conclude that one of the existing answers is best suited (I'm just including this for completeness' sake):
while (true)
{
cnt++;
if (!current->hasChild()) break;
current = current->child();
}
The while (true) will be optimized by the compiler into a regular infinite loop, so there is only one conditional statement (if you care about that).
The only thing going against this solution is if your node operation was a long piece of code. I don't mind infinite loops so much, as long as I can see where they terminate at a glance. Then again, if it were really long, it should be a function anyway.
cnt++;
while(current->hasChild())
{
cnt++;
current = current->child();
}
EDIT:
If you only want cnt++ to be in your code once:
while(true)
{
cnt++;
if(current->hasChild())
current = current->child();
else
break;
}
insideloopy:
cnt++;
if ( current->hasChild() )
{
current = current->child();
goto insideloopy;
}
I love infinite loops.
while (true) {
cnt++;
if (!current->hasChild()) break;
current = current->child();
}
Of course you can do it in many other ways (see other answers). do while, put the check in the while, etc. In my solution, I wanted to map nearly to what you are doing (an infinite goto, unless break)
You can use break to get out of the loop in the middle of the code:
while (true) {
cnt++;
if (!current->hasChild()) break;
current = current->child();
}
while (current->hasChild())
{
cnt++;
current = current->child();
}
Or am I missing something?
for(cnt++ ; current->hasChild() ; cnt++) {
current = current->child();
}
I'd investigate the possibility of making current->child() return NULL when it has no child if it doesn't already -- that seems the best possible result and leaving it undefined in this case seems error prone -- and then use:
for (; current; current = current->child())
{
cnt++;
}
No break statements:
notDone=true;
while(notDone){
cnt++;
if ( current->hasChild() ){
current = current->child();
} else {
notDone=false;
}
}