I have a contrived example to demonstrate the request for a specific functionality - I wonder if anyone has a clever trick to do this.
The following is a problem one
For both readability and performance, I think the following code can be used:
for (ii = 0;; ii++)
{
printf("%d", ii);
(ii < 3) ? (putchar(' ')) : ({ putchar('\n'); break; });
}
Actually, the above code is similar to your last code. It is readable, and it still has one conditional evaluation in each increment.
[In many ways this question should be closed as it's opinion based.]
This problem crops up often. I always opt for a solution that minimises the instructions in the iterative part.
{ /*don't pollute the outer scope with ii*/
int ii;
for (ii = 0; ii < 3; ++ii/*I've always preferred this to ii++*/) {
printf("%d ", ii);
}
printf("%d\n", ii);
}
Ternaries, if
statements etc. just obfuscate things. In my opinion.
int numberoftimes = 4
if numberoftimes > 1
{
for(ii=0; ii<numberoftimes - 1; ii++)
{
printf("%d ", ii);
}
}
printf("%d\n", numberoftimes - 1);
Either you test every time in the loop, or you test once first...
Here's a way that requires a separate initialization pass, but that has a slightly cleaner for
loop. Array sepsarray
holds the separators you want (in this example, commas so you can see them). The last element of sepsarray
is followed by a '\0'
that terminates the loop.
#include <stdio.h>
#define MAXNUM 5
//print up to this
void main() {
char sepsarray[256] = {0}; //256=arbitrary max size
int i;
char *seps=sepsarray;
for(i=0;i<MAXNUM;++i) sepsarray[i]=','; //fill in the separators
sepsarray[i]='\n'; //the last separator
for(i=0; printf("%d%c",i,*seps++),*seps; i++) /* pretend to do nothing */ ;
}
Output:
0,1,2,3,4,5
Hardly IOCCC material, but hey... :)
"Brute force" and ternary condition solution have the same complexity, but the second one is less "readable".
You can do a simple method print:
void print() {
int i = 0;
for(i=0; i != size - 1; ++i) {
printf("%i ",i);
}
printf("%i\n", i);
}
I think it is efficient and readable too.
In this way you reduce cyclomatic complexity of your alghotitm.
I have used the following type of construct for this situation. It is not more efficient (still has a condition at each iteration), but I like it because it results in a single printf
:
char *sep = " ";
for(ii=0; ii<4; ii++) {
if ( ii == 3 )
sep = "\n";
printf( "%d%s", ii, sep );
}