When I run my code and select option 3, no matter the number I input, it always returns "No good, ...".
My code works fine for option 2 and will give me the correct cout statement, so I don't understand what the problem is with my code in option 3, as they're basically the same.
You're missing the point of logical operators, since first if and second if are not the same. You're requiring a number to be both lesser than 50 AND bigger than 75, in order to enter that if statement, which can never be true. You might want to switch to an or (||).
Related
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.
#include<iostream.h>
void main()
{
int A=5,B=10;
for(int I=1;I<=2;I++)
{
cout<<"Line1="<<A++<<"&"<<B-2<<endl;
cout<<"Line2="<<++B<<"&"<<A+B<<endl;
}
}
The output of this program is
Line1=5&8
Line2=11&16
Line1=6&9
Line2=12&18
I thought that it will produce 17 and 19 in place of the 16 and 18 in the second and fourth lines of the output. This is because, in the first run of the loop, first the value of A is 5 and the first command prints 5&8 and should increment the value of A by 1, making it 6. In the second command it should print 11&(6+11) which should print 11&17 but the output is not that.
Where is the loophole in my reasoning??
Im not an expert on the subject, but I believe it is because of the order of operations that are performed in the background.
Mainly "<<" is something called an overloaded operator, which basicly means that someone, somewhere wrote what it should do, and how to do it.
And if you have a bunch of things written one after the other, like you have:
cout<<"Line2="<<++B<<"&"<<A+B<<endl;
The compiler has to do some fancy tricks to make it work.
The way the program runs through such code, is from right to left.
So in essence it kinda runs in reverse to the way you would think it does.
First it pushes endl, then it does A+B and pushes it, then it pushes &, then it increments B and it also pushes it, finaly it pushes Line2= forming the complete "sentence". These are then taken to the console (or whatever else you might have) to be printed to your screen at once.
As a solution to the issue, try separating cout into 2 lines; something like this:
cout <<"Line2="<<++B<<"&";
cout <<A+B<<endl;
Or ,if allowed to, try swaping ++B and A+B, this should also solve the issue, however your results will also be reversed.
cout<<"Line2="<<A+B<<"&"<<++B<<endl;
tl;dr: A+B happendes before B++, doing them in spearate lines or swaping the positions should solve the problem
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!
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
So I'm reading http://learnyouahaskell.com/starting-out as it explains lists, and using ghci on Vista 64. It says that [2,4..20] steps by 2 from 4 to 20. This works. It says [20,19..1] goes from 20 to 1, but doesn't explain. I take it that the first number is NOT the step, the step is the difference between the 1st and 2nd number. This is confirmed by [4,4..20] which hangs (no error message, must kill console). This is unlike operators like !! and take which check the index's range and give an error message.
My question is: is this a bug on Vista port or is that the way it's supposed to be?
[x,y..z] does indeed step from x to z by step y-x. When y-x is 0 this leads to an infinite list. This is intended behavior.
Note that if you use the list in an expression like take 20 [2,2..20], ghci won't try to print the whole list (which is impossible with infinite lists of course) and it won't "hang".
Quoting this book:
[n,p..m] is the list of numbers from n to m in steps of p-n.
Your list [4,4..20] "hangs", because you have a step of 4-4=0, so it's an infinite list containing only the number 4 ([4, 4, 4, 4...]).
Haskell allows infinite lists and as the Haskell is the "lazy evaluation language", meaning it will only compute what is necessary to give you the result, so the infinite structures are allowed in Haskell.
In Haskell you could compute something like "head[1..]". This is because Haskell only calculates what is required for the result. So in the example above it would generate only the first element of the infinite list (number 1) and head would return you this element (number 1).
So, in that case program will terminate! However, if you calculate [1..] (infinite list) program won't terminate. Same applies to your example, you created an infinite list and there is no way of terminating it.
That syntax basically is derived from listing the whole list. [1,3,5,7,9,11,13,15,17,19] for example can be shortened by simply omitting the obvious parts. So you could say, if I specify the first two elements, it is clear how it would continue. So the above list equals to [1,3..19].
It's worth noting that the .. syntax in lists desugars to the enumFrom functions given by the Enum typeclass:
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:Enum