For loop should be well-formed - c

MISRA C-2012 Control Flow Expressions (MISRA C-2012 Rule 14.2)
misra_c_2012_rule_14_2_violation: The expression i used in the for loop clauses is modified in the loop body.
for( i = 0; i < FLASH; i++ )
{
if( name.see[i] == 0xFF )
{
name.see[ i ] = faultId | mnemonicType;
modify_expr: Modifying the expression i.
i = FLASH-1; /* terminate loop */
}
}

You aren't allowed to modify the loop iterator i inside the loop body, doing so is senseless and very bad practice. Replace the obfuscated code i = FLASH-1; with break;.

Misra C 2004 rule 13.6 (14.2 in the 2012 edition) says
Numeric variables being used within a for loop for iteration counting shall not be modified in the body of the loop.
The code modifies i in order to finish the for loop (as the comment confirms). This is a violation of the rule.
Misra C 2004 rule 14.6 says:
For any iteration statement there shall be at most one break statement used for loop termination.
Hence you can replace the offending code with a simple break statement and still conform:
for (i = 0; i < FLASH; i++) {
if (name.see[i] == 0xFF) {
name.see[i] = faultId | mnemonicType;
break;
}
}
Yet Misra says you can only do this if there is a single break statement in the loop. What if you want to test 2 different cases, handle them differently and break the loop on each of them. Using 2 break statements seems an obvious choice, but for compliance you would need to add an extra variable do_break, set it in the places where you want to break and test it just once at the end of the body to execute the break statement. Not a very good practice IMHO...
Note these facts about Misra C coding standards:
Misra renumbered the rules from one edition to the next, a necessary change creating some confusion.
The rules are not available in open source. This would help spread some good practices, but arguably prevented some questionable ones.

This for loop
for( i = 0; i < FLASH; i++ )
{
if( name.see[i] == 0xFF )
{
name.see[ i ] = faultId | mnemonicType;
i = FLASH-1; /* terminate loop */
}
}
is not clear for readers of the code.
Even if you will write
for( i = 0; i < FLASH; i++ )
{
if( name.see[i] == 0xFF )
{
name.see[ i ] = faultId | mnemonicType;
break;
}
}
then using the break statement is not a good approach. Each code block should have one entry point and one exit point.
In fact what you need is to find an element that satisfies the condition
name.see[i] == 0xFF
and is such an element exists then change it.
So it is better to write a while loop instead of the for loop the following way
i = 0;
wjile ( i < FLASH && name.see[i] != 0xFF ) i++
if ( i != FLASH ) name.see[ i ] = faultId | mnemonicType;
The advantage of this approach is that the while loop as is can be formed as a body of a function that finds an element in the array. It will be enough just to add the return statement
return i;

Related

I have problem translating C code in fortran

for(i=1;i<=ntype;i++)
for(cnt=0,j=1;j<=nbeta[i];j++) {
cnt++;
pos[i][cnt]=j;
if (lll[i][j]==0) {
for(kk=1;kk<=kkbeta[i];kk++)
bfunc[i][cnt][kk]=bfunctmp[i][j][kk];
llltmp[i][cnt]=lll[i][j];
} // if
if (lll[i][j]>0) {
for(kk=1;kk<=kkbeta[i];kk++)
bfunc[i][cnt][kk]=0.5*(bfunctmp[i][j ][kk]+
bfunctmp[i][j+1][kk]);
llltmp[i][cnt]=lll[i][j];
j++;
} // if
} // j,i
!my translated fortran code is
do i =1,ntype
cnt =0
do j =1,nbeta(i)
cnt = cnt+1
pos(i,cnt) =j
if(lll(i,j) ==0) then
do kk =1, kkbeta(i)
bfunc(i,cnt,kk)= bfunctmp(i,j,kk)
end do !end kk
llltmp(i,cnt) =lll(i,j)
! write(*,*)i,j,lll(i,j)
! write(*,*)i,cnt,llltmp(i,cnt) ! '(5x,3I5)'
end if
! cnt1 =j
if(lll(i,j) > 0) then
do kk =1, kkbeta(i)
bfunc(i,cnt,kk)= 0.5 *(bfunctmp(i,j,kk) + bfunctmp(i,j+1,kk))
end do !end kk
llltmp(i,cnt) =lll(i,j)
j =j+1
end if
end do !end j
end do !end i
! A do-variable within a DO body shall not appear in a variable definition context. [j]
I am looking forward to solve this issue soon. Thank you!
As #TomKarzes remarked in comments, you may not assign to the control variable of a DO loop within the body of that loop. Sometimes you can resolve such issues by using a different variable, instead. In your code, however, the objective of the j=j+1 appears to be to skip a loop iteration, and you simply cannot do that in a DO loop.
You can, however, replace your DO loop with a DO WHILE loop:
j = 1
do while (j <= nbeta(i))
! ...
if (lll(i,j) > 0) then
! ...
j = j + 1
end if
j = j + 1
end do
That should work for your particular code, but you must take considerable care when making such a transformation. There are at least these considerations that must be accounted for:
In an iterated DO loop, the loop variable is automatically incremented after each execution of the loop body, even if execution of the body terminates early by execution of a CYCLE statement. In a DO WHILE loop, however, variables are modified only by statements that are executed, so a CYCLE will not, itself, cause any variable to be updated.
The number of iterations for an iterated DO loop to perform is computed before the first iteration is performed, based on data (such as the value of nbeta(i)) gathered when execution reaches the DO statement. That number of iterations can be changed only by prematurely discontinuing the loop via an EXIT, RETURN, GOTO, or STOP statement, or by executing a procedure that causes the program to terminate. On the other hand, the condition of a DO WHILE is evaluated before every iteration.

What is the cause for 'Segmentation fault (core dumped) '

I wrote a program to find the prime factors of a number using recursion. I am getting an run time error. What is the cause?
#include<stdio.h>
int main () {
int num , i = 2 ;
printf ( " Enter the number to find the prime factors\n ") ;
scanf ( "%d", &num ) ;
printf ( " The factors are :\n") ;
pf ( num , i ) ;
}
int pf ( int num , int i){
if ( num % i == 0 ){
if ( checkprime(i) == 1){
printf ( " %d " , i ) ;
num = num / i ;
}
}
if ( num > 1 ){
i++ ;
pf ( num , i ) ;
}
}
int checkprime ( int i){
int j ;
if (i==2)
return 1 ;
for ( j = 2 ; j < i ; j++ ){
if ( (i % j) == 0 )
return 0 ;
else
return 1 ;
}
if ( i==j )
return 1 ;
}
Sample run:
Enter the number to find the prime factors
12
The factors are :
Segmentation fault (core dumped)enter code here
This looks like a learning exercise you want to solve on your own, so I won’t be writing code for you. (If you try to plug the sample code here into your program without refactoring, it won’t work.)
In the spirit of teaching you to fish, the first thing you should do is compile without optimization, with debugging symbols, and with all warnings turned on. On gcc/clang/icc, the flags for that will be something like:
-std=c11 -Wall -Wextra -Wpedantic -Wconversion -g
This code should not even compile. You’re repeatedly falling through to the end of a function that does not return the void type, yet falls through with no return statement. Not only that, you define pf() and checkprime() after they are called with no prototype! That’s not the only bug, but let’s start there.
You’re technically supposed to have a return from main(), too, but so many programs don’t that the C committee just gave in and said it’s optional.
A good next step to catch a bug is to load the program in a debugger, put a breakpoint on the function you want to debug, and single-step through it.
When you do this, you see that the program goes into an infinite loop if you give it, let’s say, 4, and if you do give it an answer that terminates, such as pf(1, 2), it will fall through all the if blocks and never reach a return statement.
So you need to debug your algorithm, but first, you need to make sure that every path through your function reaches a return statement. (You might also, if you don’t actually need a return value, declare void pf(int, int).
One way I like to do this (but doesn’t seem to be common in C) is to write if-else-return with the ? operator, such as:
return (num <= 1) ? 1 : // No more factors.
(num % i == 0) ? pf( num/i, i ) : // Prime factor, with possible multiplicity.
pf( num, i+1 ); // Not a factor. Keep looking.
This of course doesn’t work here because it never prints the factors. (It’s based on functional-style code that isn’t supposed to have side-effects like doing I/O.) One way to fix it would be to rewrite with if/then/else. Another is to store the factors in a data structure such as a dynamic array or linked list, and return that. Another is to print before the complex return. Another is to have the branch that should print a factor call a mutually-recursive function that prints and then calls pf(). A really ugly hack that you shouldn’t do is to use the comma operator. Pick the one you like the best.
This has the advantage of being tail-recursive, so it might go into an infinite loop but will not cause a stack overflow.
If you don’t like this style, another approach that some shops use to prevent this bug from happening is to write the function with nested if blocks that set a variable like int to_return = UNSET;. Then, every branch sets to_return to the proper value and you can finish with something like
if (foo)
to_return = 1;
else
to_return = f(i);
asseert(to_return != UNSET);
return to_return;
That way, the compiler ensures that you’re returning from a valid branch, or if you do forget to set a return value along some path, crashes and tells you where and why, not “Segmentation fault (core dumped).”

do ... while macro/function with different conditions

I have the following code:
/* some calculation */
do {
/* data acquire and calculation */
} while (CONDITION);
My condition looks like one of the following:
(( A || B ) && C )
( A && C )
Note that I use these conditions with different statements for A, B and C. However the pre-calculation and everything inside the loop is always the same. I use this block several times in my code and wondered if there is a possibility to put it in a define or in a function to let the code look cleaner.
Is there a nice and reasonable way to achieve the loop with different statements?
I already thought about a function call in a while loop like
while (DoMyLoop( CONDITION, calculationParams ));
But with this solution I wouldn't have the pre-calculation in my one-liner.
How can I get my code block in a nice one-liner (or more if necessary, as long as it's easy to understand and maintain)?
Some additional (maybe irrelevant) information:
In my loop I receive a byte array and depending on the situation I have to loop until a specific bit changes, therefore the A or B.
C is a timeout condition.
Here is some code with variables
unsigned char data[10] = { 0 };
long intervalMS = 0;
/* precalc */
gettimeofday( &stopTimeout, NULL );
gettimeofday( &startTimeout, NULL );
do {
receiveCall( data );
gettimeofday( &stopTimeout, NULL );
intervalMS = (stopTimeout.tv_sec - startTimeout.tv_sec) * 1000 +
(stopTimeout.tv_usec - startTimeout.tv_usec) / 1000;
} while ( (data[0] & 0x01) && intervalMS < 200);
The A part of the condition can also look like ((data[2] & 0x02) || data[3] == 0x12).
What about next solution?
for (precalculation (); CONDITION; somethingWith (calculationParams));
precalculation () is executed once, the CONDITION is evaluated at every iteration and somethingWith (calculationParams) take the place in of the incrementation. The body of the for loop is empty.
Pure C beauty.
Obviously, precalculation and somethingWith (calculationParams) must become a new function.
First of all, please note that do {} while(something) is equivalent to something=true; while something{}. The former saves a bit of extra execution in case you don't want the initialization part.
How can I get my code block in a nice one-liner
There is nothing wrong with your code. } while ( (data[0] & 0x01) && intervalMS < 200); is perfectly clear to me - another C programmer.
You check if the lsb is set and you check a timer interval. The only way this code could be improved would be to explain why you check the lsb - which you can do with a comment (do you check if a number is odd or do you read a bit in bit-field etc).
Now what you can and should do, is to put the whole snippet inside a function and give it a meaningful name. There's the nice one-liner.

Do goto statements in C and assembly break locality of reference thereby decreasing performance?

I wrote a program in C that selects random words from a book in txt file format and prints them out one by one using goto statements. When I run the program it takes about 2 to 3 minutes to start running. Could it be that goto statements break locality of reference and drastically decrease performance? Also does jmp in assembly act as goto breaking locality of reference as well?
Eventually all flow control results in some form of jump. Most only jump locally so will not break locality. If your program is taking minutes to start, you probably have it doing something like reading that (large?) text file before it does anything else. Try it with a small file and see how it runs then.
This is a very vague question. Gotos might impair locality or might not, it depends on the case. But even when this holds, it is not necessarily bad. For this case, you need to post some code. Take a look at these 2 examples:
CASE 1:
for(int i = 0; i<SIZE ; i++){
if( strcmp(words[i],"key")==0 )
goto end;
}
end:
printf("FOUND!\n");
return 1;
CASE 2:
int flag = 0;
for(int i = 0; i<SIZE ; i++){
if( strcmp(words[i],"key")==0 )
flag = 1;
}
end:
if(flag) printf("FOUND!\n");
Of course that CASE 2 enjoys more locality than the first, but CASE 1 would be more efficient (i.e. it would take less time to run), except for the case where "key" is on the last position of the array.

For vs. while in C programming?

There are three loops in C: for, while, and do-while. What's the difference between them?
For example, it seems nearly all while statements can be replaced by for statements, right? Then, what's the advantage using while?
A while loop will always evaluate the condition first.
while (condition) {
//gets executed after condition is checked
}
A do/while loop will always execute
the code in the do{} block first
and then evaluate the condition.
do {
//gets executed at least once
} while (condition);
A for loop allows you to initiate a counter variable, a check condition, and a way to increment your counter all in one line.
for (int x = 0; x < 100; x++) {
//executed until x >= 100
}
At the end of the day, they are all still loops, but they offer some flexibility as to how they are executed.
Here is a great explanation of the reasoning behind the use of each different type of loop that may help clear things up. Thanks clyfe
The main difference between the for's
and the while's is a matter of
pragmatics: we usually use for when
there is a known number of iterations,
and use while constructs when the
number of iterations in not known in
advance. The while vs do ... while
issue is also of pragmatics, the
second executes the instructions once
at start, and afterwards it behaves
just like the simple while.
For loops are especially nice because they are concise. In order for this for loop:
for (int x = 0; x < 100; x++) {
//executed until x >= 100
}
to be written as a while loop, you'd have to do the following:
int count = 0;
while (count < 100) {
//do stuff
count++;
}
In this case, there's just more stuff to keep up with and the count++; could get lost in the logic. This could end up being troublesome depending on where count gets incremented, and whether or not it should get incremented before or after the loop's logic. With a for loop, your counter variable is always incremented before the next iteration of the loop, which adds some uniformity to your code.
For the sake of completeness, it's probably meaningful to talk about break and continue statements here which come in handy when doing loop processing.
break will instantly terminate the current loop and no more iterations will be executed.
//will only run "do stuff" twice
for (int x = 0; x < 100; x++) {
if (x == 2) {
break;
}
//do stuff
}
continue will terminate the current iteration and move on to the next one.
//will run "do stuff" until x >= 100 except for when x = 2
for (int x = 0; x < 100; x++) {
if (x == 2) {
continue;
}
//do stuff
}
Note that in a for loop, continue evaluates the part3 expression of for (part1; part2; part3); in contrast, in a while loop, it just jumps to re-evaluate the loop condition.
If there is a strong concern about speed and performance, the best approach is to verify the code produced by the compiler at the assembly level.
For instance, the following code shows that the "do-while" is a bit faster. This because the "jmp" instruction is not used by the "do-while" loop.
BTW, in this specific example, the worst case is given by the "for" loop. :))
int main(int argc, char* argv[])
{
int i;
char x[100];
// "FOR" LOOP:
for (i=0; i<100; i++ )
{
x[i] = 0;
}
// "WHILE" LOOP:
i = 0;
while (i<100 )
{
x[i++] = 0;
}
// "DO-WHILE" LOOP:
i = 0;
do
{
x[i++] = 0;
}
while (i<100);
return 0;
}
// "FOR" LOOP:
010013C8 mov dword ptr [ebp-0Ch],0
010013CF jmp wmain+3Ah (10013DAh)
for (i=0; i<100; i++ )
{
x[i] = 0;
010013D1 mov eax,dword ptr [ebp-0Ch] <<< UPDATE i
010013D4 add eax,1
010013D7 mov dword ptr [ebp-0Ch],eax
010013DA cmp dword ptr [ebp-0Ch],64h <<< TEST
010013DE jge wmain+4Ah (10013EAh) <<< COND JUMP
010013E0 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
010013E3 mov byte ptr [ebp+eax-78h],0
010013E8 jmp wmain+31h (10013D1h) <<< UNCOND JUMP
}
// "WHILE" LOOP:
i = 0;
010013EA mov dword ptr [ebp-0Ch],0
while (i<100 )
{
x[i++] = 0;
010013F1 cmp dword ptr [ebp-0Ch],64h <<< TEST
010013F5 jge wmain+6Ah (100140Ah) <<< COND JUMP
010013F7 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
010013FA mov byte ptr [ebp+eax-78h],0
010013FF mov ecx,dword ptr [ebp-0Ch] <<< UPDATE i
01001402 add ecx,1
01001405 mov dword ptr [ebp-0Ch],ecx
01001408 jmp wmain+51h (10013F1h) <<< UNCOND JUMP
}
// "DO-WHILE" LOOP:
i = 0;
. 0100140A mov dword ptr [ebp-0Ch],0
do
{
x[i++] = 0;
01001411 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
01001414 mov byte ptr [ebp+eax-78h],0
01001419 mov ecx,dword ptr [ebp-0Ch] <<< UPDATE i
0100141C add ecx,1
0100141F mov dword ptr [ebp-0Ch],ecx
01001422 cmp dword ptr [ebp-0Ch],64h <<< TEST
01001426 jl wmain+71h (1001411h) <<< COND JUMP
}
while (i<100);
For the sake of readability
They're all interchangeable; you could pick one type and use nothing but that forever, but usually one is more convenient for a given task. It's like saying "why have switch, you can just use a bunch of if statements" -- true, but if it's a common pattern to check a variable for a set of values, it's convenient and much easier to read if there's a language feature to do that
If you want a loop to execute while a condition is true, and not for a certain number of iterations, it is much easier for someone else to understand:
while (cond_true)
than something like this:
for (; cond_true ; )
Remember, a for loop is essentially a fancy while loop. They're the same thing.
while <some condition is true> {
// do some stuff
// possibly do something to change the condition
}
for ( some var, <some condition is true>; increment var ) {
}
The advantage of a for loop is that it's harder to accidentally do an infinite loop. Or rather, it's more obvious when you do one because you generally put the loop var in the initial statement.
A while loop is more clear when you're not doing a standard incrementing pattern. For example:
int x = 1;
while( x != 10 ) {
if ( some condition )
x = 10;
else
x += 5;
}
You should use such a loop, that most fully conforms to your needs.
For example:
for(int i = 0; i < 10; i++)
{
print(i);
}
//or
int i = 0;
while(i < 10)
{
print(i);
i++;
}
Obviously, in such situation, "for" looks better, than "while".
And "do while" shoud be used when some operations must be done already before the moment when condition of your loop will be checked.
Sorry for my bad english).
One common misunderstanding withwhile/for loops I've seen is that their efficiency differs. While loops and for loops are equally efficient. I remember my computer teacher from highschool told me that for loops are more efficient for iteration when you have to increment a number. That is not the case.
For loops are simply syntactically sugared while loops, and make iteration code faster to write.
When the compiler takes your code and compiles it, it is translating it into a form that is easier for the computer to understand and execute on a lower level (assembly). During this translation, the subtle differences between the while and for syntaxes are lost, and they become exactly the same.
A for suggest a fixed iteration using an index or variants on this scheme.
A while and do... while are constructions you use when there is a condition that must be checked each time (apart from some index-alike construction, see above). They differ in when the first execution of the condition check is performed.
You can use either construct, but they have their advantages and disadvantages depending on your use case.
I noticed some time ago that a For loop typically generates several more machine instructions than a while loop. However, if you look closely at the examples, which mirror my observations, the difference is two or three machine instructions, hardly worth much consideration.
Note, too, that the initializer for a WHILE loop can be eliminated by baking it into the code, e. g.:
static int intStartWith = 100;
The static modifier bakes the initial value into the code, saving (drum roll) one MOV instruction. Of greater significance, marking a variable as static moves it outside the stack frame. Variable alignment permitting, it may also produce slightly smaller code, too, since the MOV instruction and its operands take more room than, for example an integer, Boolean, or character value (either ANSI or Unicode).
However, if variables are aligned on 8 byte boundaries, a common default setting, an int, bool, or TCHAR baked into code costs the same number of bytes as a MOV instruction.
They are all the same in the work they do. You can do the same things using any of them. But for readability, usability, convenience etc., they differ.
A difference between while and do-while is that while checks the loop condition and if this is true, the body is executed and the condition checked again. The do-while checks the condition after execution of the body, so with do-while the body is executed at least one time.
Of course you can write a while loop as a do-while and vv, but this usually requires some code duplication.
One peculiarity of the do while is that you need a semi-colon after the while to complete. It is often used in macro definitions to execute several statements only once while constraining the impact of the macro. If macros where defined as blocks, some parsing errors may occur.
One explanation among others
For loops (at least considering C99) are superior to while loops because they limit the scope of the incremented variable(s).
Do while loops are useful when the condition is dependant on some inputs. They are the most seldom used of the three loop types.
Between for and while: while does not need initialization nor update statement, so it may look better, more elegant; for can have statements missing, one two or all, so it is the most flexible and obvious if you need initialization, looping condition and "update" before looping. If you need only loop condition (tested at the beginning of the loop) then while is more elegant.
Between for/while and do-while: in do-while the condition is evaluated at the end of the loop. More confortable if the loop must be executed at least once.
WHILE is more flexible. FOR is more concise in those instances in which it applies.
FOR is great for loops which have a counter of some kind, like
for (int n=0; n<max; ++n)
You can accomplish the same thing with a WHILE, of course, as others have pointed out, but now the initialization, test, and increment are broken across three lines. Possibly three widely-separated lines if the body of the loop is large. This makes it harder for the reader to see what you're doing. After all, while "++n" is a very common third piece of the FOR, it's certainly not the only possibility. I've written many loops where I write "n+=increment" or some more complex expression.
FOR can also work nicely with things other than a counter, of course. Like
for (int n=getFirstElementFromList(); listHasMoreElements(); n=getNextElementFromList())
Etc.
But FOR breaks down when the "next time through the loop" logic gets more complicated. Consider:
initializeList();
while (listHasMoreElements())
{
n=getCurrentElement();
int status=processElement(n);
if (status>0)
{
skipElements(status);
advanceElementPointer();
}
else
{
n=-status;
findElement(n);
}
}
That is, if the process of advancing may be different depending on conditions encountered while processing, a FOR statement is impractical. Yes, sometimes you could make it work with a complicated enough expressions, use of the ternary ?: operator, etc, but that usually makes the code less readable rather than more readable.
In practice, most of my loops are either stepping through an array or structure of some kind, in which case I use a FOR loop; or are reading a file or a result set from a database, in which case I use a WHILE loop ("while (!eof())" or something of that sort).
They are pretty much same except for do-while loop. The for loop is good when you have a counter kind of variable. It makes it obvious. while loop makes sense in cases where a flag is being checked as show below :
while (!done) {
if (some condtion)
done = true;
}
while and for statements can both be used for looping in programming. It will depend on the programmer as to whether the while loop or for loop is used. Some are comfortable using while loop and some are with for loop.
Use any loop you like. However, the do...while loop can be somewhat tricky in C programming.
/*
while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks
*/
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
/*
for loop
5 bucks
for my money is greater than equal to 1 bucks 0 money >= 1
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1 1-1 => 0
end
*/
#include<stdio.h>
int main(){
int money = 5;
for( ; money >= 1; ){ 0>=1 false
printf("select chocolate \n");
printf("paying 1 bucks to the shopkeeper\n");
money = money - 1; 1-1 = 0
printf(" remaining money =%d\n", money);
printf("\n\n");
}
return 0;
}
For better understanding please visit https://www.youtube.com/watch?v=_vdvyzzp-R4&t=25s

Resources