A single C++ variable has conflicting values in debugger? - c++

Please see the screenshot below. I noticed some erroneous results in my code so I went to debug.
As you can see, I put a break point when the variable 'latest' is equal to "5". BUT, apparently the application is hitting on this break point even thought 'latest' is equal to "2", not "5". Any idea what is going on here?

Format your code like this (>> denoting the breakpoint):
if (latest == "5")
{
>> ;
}
rather than this:
>> if (latest == "5") {;}
In the latter case the breakpoint is at the if, not at the ; inside the {}.
Cramming too many statements on the same line makes step by step debugging painful and makes the code less readable.

I put a break point when the variable latest is equal to "5"
No, you put a breakpoint where the variable latest is compared to "5". The comparison has to happen before the if statement knows which branch to take.

Your code rather than this:
if (latest == "5") {;}
Only use single-line if statements on a single line
The problem occurs when a single-line if the statement is broken up into two lines. While the compiler sees this as one statement guarded by a single condition, humans often accidentally read this is an if block, whether there are curly braces or not, thanks to the indentation. Humans notice the indentation, the compiler does not.
if (latest == "5")
;
If the statement you’re guarding is small, and not worth the extra heft of curly braces, just put it on the same line.

Related

if/else coding style consequences

I am a novice programmer and was in lecture one evening, we were studying the "if,else" coding section from my professor and I was curious about an aspect of it. What I was curious about was if we have a bunch of nested if,else's in our program, is it just bad coding style to end an if,else with an "else,if" line of code instead of if "x", else "y"? For example,
if "x"
else if "y"
else if "z"
end
compared to
if "x"
else if "y"
else "z"
end
It would still run the program without an error, but are there consequences later on other than having bad programming style?
Behind the curtain JS dont really have else if, all it is doing is generating another if statement when parsed.
e.g:
if(foo){
} else if (baz){
}
becomes
if (foo){
} else {
if (baz){
}
}
So the reason for using another else if in the end instead of else is when you want to control the else statement as-well and not just pass to that case everything else that don't fit in your first condition... (In order to control the else condition and filter it to the necessary items only)
if you do have a really long statement with a lot of else-if conditions you should consider using switch statement instead.
It all depends on what you are looking to do. The former example makes sure that all IF requirements are met. There would be instances that none of the IFs get hit in this case.
In the latter example however, ELSE "Z" would get hit for sure if all above IFs fail. This would be useful if you are assigning a variable within your IFs - your variable will definitely have a value at the end of the IF statement. If it was as in the first example, the variable will be null and might result in a null error if you try to use it later.
If there are a lot of if-thens, I would checkout the case/switch statement as well, as it is more neater to implement.
Also, remember to comment your code well - especially explaining what all the nested IFs are doing.

Read and write variable in an IF statement

I'm hoping to perform the following steps in a single IF statement to save on code writing:
If ret is TRUE, set ret to the result of function lookup(). If ret is now FALSE, print error message.
The code I've written to do this is as follows:
BOOLEAN ret = TRUE;
// ... functions assigning to `ret`
if ( ret && !(ret = lookup()) )
{
fprintf(stderr, "Error in lookup()\n");
}
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement. As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time, failing immediately when evaluating an operand to false rather than evaluating them all. If so, then I expect the code to follow the steps I wrote above.
I've used assignments in IF statements a lot and I know they work, but not with another read beforehand.
Is there any reason why this isn't good code? Personally, I think it's easy to read and the meaning is clear, I'm just concerned about the compiler maybe not producing the equivalent logic for whatever reason. Perhaps compiler vendor disparities, optimisations or platform dependencies could be an issue, though I doubt this.
...to save on code writing This is almost never a valid argument. Don't do this. Particularly, don't obfuscate your code into a buggy, unreadable mess to "save typing". That is very bad programming.
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement.
Correct. It has little to do with the if statement in itself though, and everything to do with the operators involved.
As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time
Well, yes... but there is operator precedence and there is order of evaluation of subexpressions, they are different things. To make things even more complicated, there are sequence points.
If you don't know the difference between operator precedence and order of evaluation, or if you don't know what sequence points are, you need to instantly stop stuffing as many operators as you can into a single line, because in that case, you are going to write horrible bugs all over the place.
In your specific case, you get away with the bad programming just because as a special case, there happens to be a sequence point between the left and right evaluation of the && operator. Had you written some similar mess with a different operator, for example ret + !(ret = lookup(), your code would have undefined behavior. A bug which will take hours, days or weeks to find. Well, at least you saved 10 seconds of typing!
Also, in both C and C++ use the standard bool type and not some home-brewed version.
You need to correct your code into something more readable and safe:
bool ret = true;
if(ret)
{
ret = lookup();
}
if(!ret)
{
fprintf(stderr, "Error in lookup()\n");
}
Is there any reason why this isn't good code?
Yes, there are a lot issues whith such dirty code fragments!
1)
Nobody can read it and it is not maintainable. A lot of coding guidlines contain a rule which tells you: "One statement per line".
2) If you combine multiple expressions in one if statement, only the first statements will be executed until the expression is defined! This means: if you have multiple expressions which combined with AND the first expression which generates false will be the last one which will be executed. Same with OR combinations: The first one which evaluates to true is the last one which is executed.You already wrote this and you! know this, but this is a bit of tricky programming. If all your colleges write code that way, it is maybe ok, but as I know, my colleagues will not understand what you are doing in the first step!
3) You should never compare and assign in one statement. It is simply ugly!
4) if YOU! already think about " I'm just concerned about the compiler maybe not producing the equivalent logic" you should think again why you are not sure what you are doing! I believe that everybody who must work with such a dirty code will think again on such combinations.
Hint: Don't do that! Never!

Method's Curly brackets do not match when code to long

I have a C++ method with multiple nested "if statements" which are enclosed in the curly brackets of the method. When using Gedit's matching curly brackets, I was checking to ensure that all my curly brackets were correctly matched.
Problem: Gedit stated that my last two curly brackets were " out of range"!
I checked same code using Geany, and it showed correct matches for all my curly brackets.
However, when compiling, the method's local variables defined at the beginning of the method, were not recognized within some latter written nested "if statements" within the method. Is there a limit of the number line codes contained between curly brackets? Or, is there a limit of nested "if and else if statements" that would cause this problem?
Is there a limit of the number line codes contained between curly brackets?
Only available disk space and memory.
Or, is there a limit of nested "if and else if statements" that would cause this problem?
Ditto.
Clearly you are mistaken about your braces matching. If you have a method that is so long you can't be sure, refactor it.
There are obviously limits, since the compiler has to keep track
of everything in memory, and memory is finite. I've actually
had an out of memory error with g++ (with machine generated
code). Reaching the limit should result in a compile time
error, however.
Practically, for hand written code, you can consider that there
are no limits on a modern machine. You generally shouldn't have
more than about ten or fifteen lines in a function (although
there are exceptions), and you shouldn't nest more than about
two levels. Of course, one of the cases where more lines might
be justified is a long sequence of if/else if, and in the
case of if/else if, the compiler sees more levels of nesting
than you do. But I would still expect a modern compiler on
a modern machine to handle a couple of hundred if/else if
without a problem.
This issue has been discussed here:
http://ubuntuforums.org/showthread.php?t=1175657
It seems there is indeed a limit on the number of characters that are being searched for finding the match.

use of "else if" in c++

I have two questions -
(I)
code-fragment-1
if(<condition-statement>){
}
else if(<condition-statement-2>){
//statements-1
}
//statements-2
code-fragment-2
if(<condition-statement>){
}
else{
if(<condition-statement-2>){
//statements-1
}
//statements-2
}
Are the above two code fragments same?
(II) when are else ifs (in C++) used?
The only difference is in example 1 your Statement2 will get executed regardless of the conditions you check. In example 2, Statement2 will only get executed if your if condition is false. Other than that, they're basically the same.
No, in the first case you execute the else block only if the <condition-statement> is not verified AND only if <condition-statement-2> is verified.
In the second case you execute the else block simply if the <codition-statement> is not verified.
In this case are equivalent until you does not have any //statements-2.
About the question : when is the else if (in c++) used ?
Is used basically under the same conditions of all other languages​​ that have this construct.
else is executed as alternative to the related if, else-if is executed as alternative but with an 'attached' if to be verified, otherwise is not executed.
So they are not logically equivalent.
the syntax of an if is really
if(condition) statement;
What the {} really do is allow you to group together multiple statements. In your second example you only have one statement(the if) inside your {}s, so yes, both examples are the same, except //statements-2 always gets run when !=true
In your first code sample, statement-2 is executed unconditionally. In the second it is conditional. Not the same.
'else if' is generally to be preferred, because you can keep inserting or appending more of them indefinitely, or append an 'else', whereas with the other form you have to endlessly mess around with braces to get the same effect, and you risk altering the semantics, as indeed you have done in your second sample.

What's the difference between these 2 'if' and 'if-else' statements?

What is the difference between 2 if statements and 1 if-else statement?
int x;
cin >> x;
if (x==10)
cout << "Hello";
if (x!=10)
cout << "Hey";
int x;
cin >> x;
if (x==10)
cout << "Hello";
else
cout << "Hey";
In practice, the optimizer will probably make them exactly the same. The best thing to do in these cases is to try it - look at the assembly output of your compiler, and you'll see exactly what the difference is.
The difference is that in the second case the condition is checked and computed only once.
In the first example both are evaluated, always.
In the second example if first is true, it never gets to second.
The most important difference (to my mind) is that the first form is harder to read and is more error-prone.
The second form reads more like English: "If x is 10 then do this, else do that" whereas the first form essentially makes the two clauses unrelated. It's error prone because if you decide that the threshold 10 needs to change then you need to update it in two places rather than just one.
In terms of execution speed, I'd be very surprised if there is any difference at all. There will be two evaluations with the first form but that's the least of the problems. It's certainly not the sort of thing you should waste time optimising.
There is no visible output difference. However, it does make your code easier to read if you use the ladder one
if (x==10) //matches only if x is number 10 , then processor jump to next line i.e.
if (x!=10) // matches only if x is not number 10
where as
other if checked only , if the number is either 10 or anything else then 10.
In a way both will result same, but its just matter of statements.
so
in first example, both lines of if will be executed
in second example either of one is executed
So its better to use second one for performance
From a maintainability point of view the first one
violates the DRY principle.
is a lot harder to understand and modify. Not with a trivial condition, like here, but with a nice long condition you'll either have to just cut 'n paste the condition and slap a ! in front, or try to remember how De Morgan's laws were formulated... And some day that will fail, and the inverted if will fail to be the exact opposite of the first....
So, else is the way to go.
In the first block both if statement will run by the compiler...
But int the second one only 1 statement will run as both are linked with a single condition . Either if can be true or else can be true
You can understand this as considering 1st one as 'and' type
And the 2nd one as 'or' type