When working with floating-points one should use
a <= 0.0
instead of
a == 0.0
to make sure that you get the desired behaviour, as there is the problem with round-off errors when using floating-point variables.
But when using other variable types like int could it be useful to do the same? Like you have a for loop iterating over an int variable (like an index) and when it gets to a number it should do something. Should you then set the comparison to be >= instead of == when it should result in the same output? Like could there ever be a case where the == is not evaluated in the following case:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
}
And that it would be "safer" to do the following instead:
for (int i = 0; i < 10; i++)
{
if (i >= 5)
{
break;
}
}
If there is no difference between the two when it comes to coding "safe" is there any performance or readability difference or other thing that can make one choose between the ways to code?
Tried to google this but couldn't find anything stating either way. But that might have to do with the problem with searching for operators.
Am I too paranoid for asking this?
The premise of the question is wrong; blindly using a <= 0.0 instead of a == 0.0 is not a valid practice with floating point. See How dangerous is it to compare floating point values? for a treatment of the topic.
With that said, there are some cases where use of inequality relational operators are "more hardened" than use of the equality operator, and vice versa. In general, I would recommend against it since it's likely to give you a false sense of safety; for example, in the example in your question with i==5 vs i>=5, the compiler is likely to be able to prove they're the same, and optimize either to the other if needed. This means it will not necessarily do anything to protect you against stack overflows or neutrinos or any other cause by which the value of i might become something other than 0..5 outside of the defined semantics of the language.
There are also some cases where use of equality is defined by inequality is not, particularly involving pointers. If pos and end are both pointers, pos==end is well-defined as long as they are both valid. But if they are both null, while pos==end is well-defined and true, pos>=end is undefined behavior. Likewise if they both point into different arrays (in particular if end points to a sentinel not part of your array), pos==end will always be false, but pos>=end is undefined behavior.
I also find it misleading to write if (i>=5) when you know i>5 is logically impossible - it makes the reader stop to think about whether it's possible, and if not, why you wrote it that way instead of if (i==5).
The answer is, it depends. If you have a loop like this:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
}
Then there is no danger in i skipping 5.
On the other hand, if you have something like this:
volatile int i;
void interrupt(void)
{
i++;
}
void foo(void)
{
for (i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
}
}
Then i may change outside the normal flow of the program (e.g. because of an interrupt). In this case >= would be prudent.
Like could there ever be a case where the == is not evaluated
No, using == is safe. Integers represent all values within the range of the integer type used accurately. There are no surprises.
Should you then set the comparison to be >= instead of ==
As the result is the same, you can do both but I would find >= confusing. So for readability I prefer ==
is there any performance . . . that can make one choose between the ways to code
You can't tell by looking at the C code. It depends on the system (CPU) used. In general I would however doubt that you would experience any major difference.
I have been asked to comment some code and describe what it does. All was fine and I had a good handle on what was being done in the the cases of the switch but now I am unsure whether any of the cases are ever met. I don't have anyway to run or test this code currently as my main machine with all my regular software is down.
Does either of the cases of the switch get used besides the default with the conditions of this while loop? is i simply incremented to 32 and the rByte returned before it even makes the switch? What is with the ; after the conditions of the while? Shouldn't it be followed by {....} rather than ; ?
while(pCommand[--Ptr.Five] > 10 && ++i <32);
if(i==32)
{
return rByte;
}
switch(pCommand[Ptr.Five++])
{
case 2: ... (lots of code)
break;
case 4: ... (lots of cod)
break;
default: ...
break;
}
Also, how is the --Ptr.Five handled vs. the Ptr.Five++? My understanding is the first moves the pointer back and uses that value while the second uses the current value and post increments.
Am I missing something? Even moving past the ; after the conditions of the while and the lack of {} after the while, wouldnt the value of Ptr.Five be > 10 and therefore never be 2 or 4 ever?
With the ; behind the conditions of the while, would i just get bumped to32 and the following if would return the rByte?
The loop
while(pCommand[--Ptr.Five] > 10 && ++i <32);
decrements Ptr.Five and increments i until
pCommand[Ptr.Five] <= 10, or
i >= 32,
whichever happens first. Since the changes to the interesting variables are done in the loop condition, the loop body should be empty. (Not that it's particularly good style, but I've seen worse.)
If i == 32, the switch isn't reached, otherwise, if i < 32, you know that pCommand[Ptr.Five] <= 10, so both non-default cases can be reached.
The semicolon by itself is an empty statement. So doing e.g.
while (complicated_expression)
;
Is the same as:
while (complicated_expression)
{
}
It's often used when complicated_expression has side-effects, so no loop body is needed.
It's impossible to answer your question. Even if we assume that i starts at 0, who knows what value pCommand[Ptr.Five] has at the start of this code block?
Addressing some of the questions that can be answered, would it help if we rewrote the while like this:
while(pCommand[--Ptr.Five] > 10 && ++i <32)
{
/* do nothing as the body of the loop... nothing at all.
* Everything happens in the condition.
*/
}
The syntax with the semicolon is valid, if a bit confusing at first: think of what the semicolon means in C/C++ (terminates a statement) and then think of what the statement being terminates is in this case (hint: it's a "no operation").
The difference between --Ptr.Five and Ptr.Five-- is what you describe: the first variant (the pre-decrement) will decrement Ptr.Five and then return the resulting value; the second variant (the post-decrement) will decrement the Ptr.Five but return the value before the decrement.
while(pCommand[--Ptr.Five] > 10 && ++i <32);
doesn't have a body, but the loop condition itself has side-effects, so it does do something.
We could re-write this as:
while (1) {
--Ptr.Five;
if (pCommand[Ptr.Five] <= 10)
break;
++i;
if (i == 32)
break;
}
if (i == 32) {
/* we never hit the pCommand condition */
}
As for why:
it searches backwards through pCommand, from offset Ptr.Five to at most 32 entries earlier, looking for a value <= 10
if it doesn't find such a value within 32 entries, it returns rByte
if it does find such a value, it switches on it and does some work
PtrFive is incremented to indicate the next entry after this value, after the switch is dispatched
Also, how is the --Ptr.Five handled vs. the Ptr.Five++? My understanding is the first moves the pointer back and uses that value while the second uses the current value and post increments.
That's exactly correct. In:
pCommand[--Ptr.Five] > 10
Ptr.Five is decremented before the rest of the expression is evaluated, whereas in:
pCommand[Ptr.Five++]
the expression is evaluated with the old value of Ptr.Five, and then it's incremented right after. Here, that means the switch is based on the old entry in pCommand (the one that ended the while loop because it's <= 10), but Ptr.Five is incremented before code inside the cases executes.
A quick note on side-effects: as John Bode points out in a comment, my description of the pre-decrement and post-increment expressions isn't quite accurate.
This is because storing the new value into Ptr.Five doesn't have to happen right away.
However since it does have to happen (as if) by the next sequence point, which is here the &&, there's no real ambiguity.
This generally only becomes an issue if you string multiple interdependent side-effecting expressions together in a single statement. So, you know, try and avoid that.
Presuming i started at 0 -- The while loop is parsing through 31 elements (1-31) of the pCommand array, decrementing Ptr.Five before checking the value, looking for a value that is less than 10. If it does not find one, the function returns rByte -- it then checks the value of pCommand[Ptr.Five] before it increments... therefore, the value used in the switch is the same as the value used in the while conditional. The value could well be any of the switch conditions as we know it is less than 10
Would it be possible to implement an if that checks for -1 and if not negative -1 than assign the value. But without having to call the function twice? or saving the return value to a local variable. I know this is possible in assembly, but is there a c implementation?
int i, x = -10;
if( func1(x) != -1) i = func1(x);
saving the return value to a local variable
In my experience, avoiding local variables is rarely worth the clarity forfeited. Most compilers (most of the time) can often avoid the corresponding load/stores and just use registers for those locals. So don't avoid it, embrace it! The maintainer's sanity that gets preserved just might be your own.
I know this is possible in assembly, but is there a c implementation?
If it turns out your case is one where assembly is actually appropriate, make a declaration in a header file and link against the assembly routine.
Suggestion:
const int x = -10;
const int y = func1(x);
const int i = y != -1
? y
: 0 /* You didn't really want an uninitialized value here, right? */ ;
It depends whether or not func1 generates any side-effects. Consider rand(), or getchar() as examples. Calling these functions twice in a row might result in different return values, because they generate side effects; rand() changes the seed, and getchar() consumes a character from stdin. That is, rand() == rand() will usually1 evaluate to false, and getchar() == getchar() can't be predicted reliably. Supposing func1 were to generate a side-effect, the return value might differ for consecutive calls with the same input, and hence func1(x) == func1(x) might evaluate to false.
If func1 doesn't generate any side-effect, and the output is consistent based solely on the input, then I fail to see why you wouldn't settle with int i = func1(x);, and base logic on whether or not i == -1. Writing the least repetitive code results in greater legibility and maintainability. If you're concerned about the efficiency of this, don't be. Your compiler is most likely smart enough to eliminate dead code, so it'll do a good job at transforming this into something fairly efficient.
1. ... at least in any sane standard library implementation.
int c;
if((c = func1(x)) != -1) i = c;
The best implementation I could think of would be:
int i = 0; // initialize to something
const int x = -10;
const int y = func1(x);
if (y != -1)
{
i = y;
}
The const would let the compiler to any optimizations that it thinks is best (perhaps inline func1). Notice that func is only called once, which is probably best. The const y would also allow y to be kept in a register (which it would need to be anyway in order to perform the if). If you wanted to give more of a suggestion, you could do:
register const int y = func1(x);
However, the compiler is not required to honor your register keyword suggestion, so its probably best to leave it out.
EDIT BASED ON INSPIRATION FROM BRIAN'S ANSWER:
int i = ((func1(x) + 1) ?:0) - 1;
BTW, I probably wouldn't suggest using this, but it does answer the question. This is based on the SO question here. To me, I'm still confused as to the why for the question, it seems like more of a puzzle or job interview question than something that would be encountered in a "real" program? I'd certainly like to hear why this would be needed.
Many times I need to do things TWICE in a for loop. Simply I can set up a for loop with an iterator and go through it twice:
for (i = 0; i < 2; i++)
{
// Do stuff
}
Now I am interested in doing this as SIMPLY as I can, perhaps without an initializer or iterator? Are there any other, really simple and elegant, ways of achieving this?
This is elegant because it looks like a triangle; and triangles are elegant.
i = 0;
here: dostuff();
i++; if ( i == 1 ) goto here;
Encapsulate it in a function and call it twice.
void do_stuff() {
// Do Stuff
}
// .....
do_stuff();
do_stuff();
Note: if you use variables or parameters of the enclosing function in the stuff logic, you can pass them as arguments to the extracted do_stuff function.
If its only twice, and you want to avoid a loop, just write the darn thing twice.
statement1;
statement1; // (again)
If the loop is too verbose for you, you can also define an alias for it:
#define TWICE for (int _index = 0; _index < 2; _index++)
This would result into that code:
TWICE {
// Do Stuff
}
// or
TWICE
func();
I would only recommend to use this macro if you have to do this very often, I think else the plain for-loop is more readable.
Unfortunately, this is not for C, but for C++ only, but does exactly what you want:
Just include the header, and you can write something like this:
10 times {
// Do stuff
}
I'll try to rewrite it for C as well.
So, after some time, here's an approach that enables you to write the following in pure C:
2 times {
do_something()
}
Example:
You'll have to include this little thing as a simple header file (I always called the file extension.h). Then, you'll be able to write programs in the style of:
#include<stdio.h>
#include"extension.h"
int main(int argc, char** argv){
3 times printf("Hello.\n");
3 times printf("Score: 0 : %d\n", _);
2 times {
printf("Counting: ");
9 times printf("%d ", _);
printf("\n");
}
5 times {
printf("Counting up to %d: ", _);
_ times printf("%d ", _);
printf("\n");
}
return 0;
}
Features:
Simple notation of simple loops (in the style depicted above)
Counter is implicitly stored in a variable called _ (a simple underscore).
Nesting of loops allowed.
Restrictions (and how to (partially) circumvent them):
Works only for a certain number of loops (which is - "of course" - reasonable, since you only would want to use such a thing for "small" loops). Current implementation supports a maximum of 18 iterations (higher values result in undefined behaviour). Can be adjusted in header file by changing the size of array _A.
Only a certain nesting depth is allowed. Current implementation supports a nesting depth of 10. Can be adjusted by redefining the macro _Y.
Explanation:
You can see the full (=de-obfuscated) source-code here. Let's say we want to allow up to 18 loops.
Retrieving upper iteration bound: The basic idea is to have an array of chars that are initially all set to 0 (this is the array counterarray). If we issue a call to e.g. 2 times {do_it;}, the macro times shall set the second element of counterarray to 1 (i.e. counterarray[2] = 1). In C, it is possible to swap index and array name in such an assignment, so we can write 2[counterarray] = 1 to acchieve the same. This is exactly what the macro times does as first step. Then, we can later scan the array counterarray until we find an element that is not 0, but 1. The corresponding index is then the upper iteration bound. It is stored in variable searcher. Since we want to support nesting, we have to store the upper bound for each nesting depth separately, this is done by searchermax[depth]=searcher+1.
Adjusting current nesting depth: As said, we want to support nesting of loops, so we have to keep track of the current nesting depth (done in the variable depth). We increment it by one if we start such a loop.
The actual counter variable: We have a "variable" called _ that implicitly gets assigned the current counter. In fact, we store one counter for each nesting depth (all stored in the array counter. Then, _ is just another macro that retrieves the proper counter for the current nesting depth from this array.
The actual for loop: We take the for loop into parts:
We initialize the counter for the current nesting depth to 0 (done by counter[depth] = 0).
The iteration step is the most complicated part: We have to check if the loop at the current nesting depth has reached its end. If so, we have do update the nesting depth accordingly. If not, we have to increment the current nesting depth's counter by 1. The variable lastloop is 1 if this is the last iteration, otherwise 0, and we adjust the current nesting depth accordingly. The main problem here is that we have to write this as a sequence of expressions, all separated by commata, which requires us to write all these conditions in a very non-straight-forward way.
The "increment step" of the for loop consists of only one assignment, that increments the appropriate counter (i.e. the element of counter of the proper nesting depth) and assigns this value to our "counter variable" _.
What about this??
void DostuffFunction(){}
for (unsigned i = 0; i < 2; ++i, DostuffFunction());
Regards,
Pablo.
What abelenky said.
And if your { // Do stuff } is multi-line, make it a function, and call that function -- twice.
Many people suggest writing out the code twice, which is fine if the code is short. There is, however, a size of code block which would be awkward to copy but is not large enough to merit its own function (especially if that function would need an excessive number of parameters). My own normal idiom to run a loop 'n' times is
i = number_of_reps;
do
{
... whatever
} while(--i);
In some measure because I'm frequently coding for an embedded system where the up-counting loop is often inefficient enough to matter, and in some measure because it's easy to see the number of repetitions. Running things twice is a bit awkward because the most efficient coding on my target system
bit rep_flag;
rep_flag = 0;
do
{
...
} while(rep_flag ^= 1); /* Note: if loop runs to completion, leaves rep_flag clear */
doesn't read terribly well. Using a numeric counter suggests the number of reps can be varied arbitrarily, which in many instances won't be the case. Still, a numeric counter is probably the best bet.
As Edsger W. Dijkstra himself put it : "two or more, use a for". No need to be any simpler.
Another attempt:
for(i=2;i--;) /* Do stuff */
This solution has many benefits:
Shortest form possible, I claim (13 chars)
Still, readable
Includes initialization
The amount of repeats ("2") is visible in the code
Can be used as a toggle (1 or 0) inside the body e.g. for alternation
Works with single instruction, instruction body or function call
Flexible (doesn't have to be used only for "doing twice")
Dijkstra compliant ;-)
From comment:
for (i=2; i--; "Do stuff");
Use function:
func();
func();
Or use macro (not recommended):
#define DO_IT_TWICE(A) A; A
DO_IT_TWICE({ x+=cos(123); func(x); })
If your compiler supports this just put the declaration inside the for statement:
for (unsigned i = 0; i < 2; ++i)
{
// Do stuff
}
This is as elegant and efficient as it can be. Modern compilers can do loop unrolling and all that stuff, trust them. If you don't trust them, check the assembler.
And it has one little advantage to all other solutions, for everybody it just reads, "do it twice".
Assuming C++0x lambda support:
template <typename T> void twice(T t)
{
t();
t();
}
twice([](){ /*insert code here*/ });
Or:
twice([]()
{
/*insert code here*/
});
Which doesn't help you since you wanted it for C.
Good rule: three or more, do a for.
I think I read that in Code Complete, but I could be wrong. So in your case you don't need a for loop.
This is the shortest possible without preprocessor/template/duplication tricks:
for(int i=2; i--; ) /*do stuff*/;
Note that the decrement happens once right at the beginning, which is why this will loop precisely twice with the indices 1 and 0 as requested.
Alternatively you can write
for(int i=2; i--; /*do stuff*/) ;
But that's purely a difference of taste.
If what you are doing is somewhat complicated wrap it in a function and call that function twice? (This depends on how many local variables your do stuff code relies on).
You could do something like
void do_stuff(int i){
// do stuff
}
do_stuff(0);
do_stuff(1);
But this may get extremely ugly if you are working on a whole bunch of local variables.
//dostuff
stuff;
//dostuff (Attention I am doing the same stuff for the :**2nd** time)
stuff;
First, use a comment
/* Do the following stuff twice */
then,
1) use the for loop
2) write the statement twice, or
3) write a function and call the function twice
do not use macros, as earlier stated, macros are evil.
(My answer's almost a triangle)
What is elegance? How do you measure it? Is someone paying you to be elegant? If so how do they determine the dollar-to-elegance conversion?
When I ask myself, "how should this be written," I consider the priorities of the person paying me. If I'm being paid to write fast code, control-c, control-v, done. If I'm being paid to write code fast, well.. same thing. If I'm being paid to write code that occupies the smallest amount of space on the screen, I short the stock of my employer.
jump instruction is pretty slow,so if you write the lines one after the other,it would work faster,than writing a loop. but modern compilers are very,very smart and the optimizations are great (if they are allowed,of course). if you have turned on your compiler's optimizations,you don't care the way,you write it - with loop or not (:
EDIT : http://en.wikipedia.org/wiki/compiler_optimizations just take a look (:
Close to your example, elegant and efficient:
for (i = 2; i; --i)
{
/* Do stuff */
}
Here's why I'd recommend that approach:
It initializes the iterator to the number of iterations, which makes intuitive sense.
It uses decrement over increment so that the loop test expression is a comparison to zero (the "i;" can be interpreted as "is i true?" which in C means "is i non-zero"), which may optimize better on certain architectures.
It uses pre-decrement as opposed to post-decrement in the counting expression for the same reason (may optimize better).
It uses a for loop instead of do/while or goto or XOR or switch or macro or any other trick approach because readability and maintainability are more elegant and important than clever hacks.
It doesn't require you to duplicate the code for "Do stuff" so that you can avoid a loop. Duplicated code is an abomination and a maintenance nightmare.
If "Do stuff" is lengthy, move it into a function and give the compiler permission to inline it if beneficial. Then call the function from within the for loop.
I like Chris Case's solution (up here), but C language doesn't have default parameters.
My solution:
bool cy = false;
do {
// Do stuff twice
} while (cy = !cy);
If you want, you could do different things in the two cycle by checking the boolean variable (maybe by ternary operator).
void loopTwice (bool first = true)
{
// Recursion is your friend
if (first) {loopTwice(false);}
// Do Stuff
...
}
I'm sure there's a more elegant way, but this is simple to read, and pretty simply to write. There might even be a way to eliminate the bool parameter, but this is what I came up with in 20 seconds.
Is there a difference in the order of the comparison operator?
#define CONST_VALUE 5
int variable;
...
if ( variable == CONST_VALUE ) // Method 1
...
OR
if ( CONST_VALUE == variable ) // Method 2
...
Is this simply a matter of preference or is there a compelling reason for a particular comparison order?
The reason some people use method 2 is because you'll get a compiler error if you mistype a = in place of the ==.
However, you'll have people (like me) who will still use method 1 because they find it more readable and if there is an error, it will be detected during testing (or, in some cases, static analysis of the code).
The only difference is that ( CONST_VALUE == variable ) makes the common typo ( CONST_VALUE = variable ) impossible to compile.
By comparison, if ( variable = CONST_VALUE ) will result in the compiler thinking you meant to assign CONST_VALUE to 'variable'.
The =/== confusion is a pretty common source of bugs in C, which is why people are trying to work around the issue with coding conventions.
Of course, this won't save you if you're comparing two variables.
And the question seems to be a duplicate of How to check for equals? (0 == i) or (i == 0)
And here's some more information: http://cwe.mitre.org/data/definitions/481.html
As others mentioned, CONST_VALUE == variable avoids the = typo.
I still do "variable == CONST_VALUE", because I think its more readable and when I see something like:
if(false == somevariable)
my bloodpressure goes up.
The first variant
if (variable == CONST_VALUE)
is better, because it is more readable. It follows the convention (also used in mathematics) that the value that changes most comes first.
The second variant
if (CONST_VALUE == variable)
is used by some people to prevent a mixup of equality checking with the assignment
if (CONST_VALUE = variable)
There are better ways to achieve that, for example enabling and taking heed of compiler warnings.
Others already pointed out the reason. = / == confusion. I prefer the first version because it follows the thought process more closely. Some compiler alleviate the confusion of = and == by giving a warning when it encounters something like
if(a=b)
in this case if you really wanted to do the assignation you're forced to write
if((a=b))
which I would write then as
if( (a=b) != 0)
to avoid the confusion.
This said, we had in our code 1 case where we had a =/== confusion and writing it the other way round wouldn't not have aided as it was a comparison between vars.