C "if" structure - c

I am learning C and my question might be silly but im confused.In a function like:
int afunction(somevariables)
{
if (someconditions)
{
do some stuff
return 1;
}
raise_error("error happened")
return 0;
}
My question is,if the if statement isnt meeted(success),then it will go to the raise_error ? in other words,does the raise_errors position act like if it was in a else statement,or its because you have to return something at the end(return 0)?or would it need a proper else statement?Basically im confused on how to make a propre if condition--if this condition isnt meet--then call raise_error.
thank you!

if the if statement isn't met (success), then it will go to the raise_error?
Yes. When if condition is not met, the control is passed to else branch if it exists; otherwise, the entire if statement is skipped.
in other words, does the raise_errors position act like if it was in a else statement?
In this case, the answer is "yes", but only because your if branch is structured in a way that terminates the function due to return statement at the end.
Without that return at the end the control would go to raise_error upon completion of the if branch.

in other words,does the raise_errors position act like if it was in a else statement
Yes. Unless raise_error() does something that exits process, the return 0 will be executed aferwards.
Basically im confused on how to make a propre if condition--if this condition isnt meet--then call raise_error.
The code is fine. But if it makes it easier to understand then you can use an else clause too.
Your code is functionally equivalent to:
int afunction(somevariables)
{
if (someconditions) {
do some stuff
return 1;
}
else {
raise_error("error happened")
return 0;
}
}

The code or line that is not under some condition will always be executed unless you get out of the code before getting to that unconditional line. You don't need else in this case since you return 1 and does not execute remaining lines

Related

Adding "else" at the end of an if-else statement [duplicate]

Our organization has a required coding rule (without any explanation) that:
if … else if constructs should be terminated with an else clause
Example 1:
if ( x < 0 )
{
x = 0;
} /* else not needed */
Example 2:
if ( x < 0 )
{
x = 0;
}
else if ( y < 0 )
{
x = 3;
}
else /* this else clause is required, even if the */
{ /* programmer expects this will never be reached */
/* no change in value of x */
}
What edge case is this designed to handle?
What also concerns me about the reason is that Example 1 does not need an else but Example 2 does. If the reason is re-usability and extensibility, I think else should be used in both cases.
As mentioned in another answer, this is from the MISRA-C coding guidelines. The purpose is defensive programming, a concept which is often used in mission-critical programming.
That is, every if - else if must end with an else, and every switch must end with a default.
There are two reasons for this:
Self-documenting code. If you write an else but leave it empty it means: "I have definitely considered the scenario when neither if nor else if are true".
Not writing an else there means: "either I considered the scenario where neither if nor else if are true, or I completely forgot to consider it and there's potentially a fat bug right here in my code".
Stop runaway code. In mission-critical software, you need to write robust programs that account even for the highly unlikely. So you could see code like
if (mybool == TRUE)
{
}
else if (mybool == FALSE)
{
}
else
{
// handle error
}
This code will be completely alien to PC programmers and computer scientists, but it makes perfect sense in mission-critical software, because it catches the case where the "mybool" has gone corrupt, for whatever reason.
Historically, you would fear corruption of the RAM memory because of EMI/noise. This is not much of an issue today. Far more likely, memory corruption occurs because of bugs elsewhere in the code: pointers to wrong locations, array-out-of-bounds bugs, stack overflow, runaway code etc.
So most of the time, code like this comes back to slap yourself in the face when you have written bugs during the implementation stage. Meaning it could also be used as a debug technique: the program you are writing tells you when you have written bugs.
EDIT
Regarding why else is not needed after every single if:
An if-else or if-else if-else completely covers all possible values that a variable can have. But a plain if statement is not necessarily there to cover all possible values, it has a much broader usage. Most often you just wish to check a certain condition and if it is not met, then do nothing. Then it is simply not meaningful to write defensive programming to cover the else case.
Plus it would clutter up the code completely if you wrote an empty else after each and every if.
MISRA-C:2012 15.7 gives no rationale why else is not needed, it just states:
Note: a final else statement is not required for a simple if
statement.
Your company followed MISRA coding guidance. There are a few versions of these guidelines that contain this rule, but from MISRA-C:2004†:
Rule 14.10 (required): All if … else if constructs shall be terminated
with an else clause.
This rule applies whenever an if statement is followed by one or more
else if statements; the final else if shall be followed by an else
statement. In the case of a simple if statement then the else
statement need not be included. The requirement for a final else
statement is defensive programming. The else statement shall either
take appropriate action or contain a suitable comment as to why no
action is taken. This is consistent with the requirement to have a
final default clause in a switch statement. For example this code
is a simple if statement:
if ( x < 0 )
{
log_error(3);
x = 0;
} /* else not needed */
whereas the following code demonstrates an if, else if construct
if ( x < 0 )
{
log_error(3);
x = 0;
}
else if ( y < 0 )
{
x = 3;
}
else /* this else clause is required, even if the */
{ /* programmer expects this will never be reached */
/* no change in value of x */
}
In MISRA-C:2012, which supersedes the 2004 version and is the current recommendation for new projects, the same rule exists but is numbered 15.7.
Example 1:
in a single if statement programmer may need to check n number of conditions and performs single operation.
if(condition_1 || condition_2 || ... condition_n)
{
//operation_1
}
In a regular usage performing a operation is not needed all the time when if is used.
Example 2:
Here programmer checks n number of conditions and performing multiple operations. In regular usage if..else if is like switch you may need to perform a operation like default. So usage else is needed as per misra standard
if(condition_1 || condition_2 || ... condition_n)
{
//operation_1
}
else if(condition_1 || condition_2 || ... condition_n)
{
//operation_2
}
....
else
{
//default cause
}
† Current and past versions of these publications are available for purchase via the MISRA webstore (via).
This is the equivalent of requiring a default case in every switch.
This extra else will Decrease code coverage of your program.
In my experience with porting linux kernel , or android code to different platform many time we do something wrong and in logcat we see some error like
if ( x < 0 )
{
x = 0;
}
else if ( y < 0 )
{
x = 3;
}
else /* this else clause is required, even if the */
{ /* programmer expects this will never be reached */
/* no change in value of x */
printk(" \n [function or module name]: this should never happen \n");
/* It is always good to mention function/module name with the
logs. If you end up with "this should never happen" message
and the same message is used in many places in the software
it will be hard to track/debug.
*/
}
Only a brief explanation, since I did this all about 5 years ago.
There is (with most languages) no syntactic requirement to include "null" else statement (and unnecessary {..}), and in "simple little programs" there is no need. But real programmers don't write "simple little programs", and, just as importantly, they don't write programs that will be used once and then discarded.
When one write an if/else:
if(something)
doSomething;
else
doSomethingElse;
it all seems simple and one hardly sees even the point of adding {..}.
But some day, a few months from now, some other programmer (you would never make such a mistake!) will need to "enhance" the program and will add a statement.
if(something)
doSomething;
else
doSomethingIForgot;
doSomethingElse;
Suddenly doSomethingElse kinda forgets that it's supposed to be in the else leg.
So you're a good little programmer and you always use {..}. But you write:
if(something) {
if(anotherThing) {
doSomething;
}
}
All's well and good until that new kid makes a midnight modification:
if(something) {
if(!notMyThing) {
if(anotherThing) {
doSomething;
}
else {
dontDoAnything; // Because it's not my thing.
}}
}
Yes, it's improperly formatted, but so is half the code in the project, and the "auto formatter" gets bollixed up by all the #ifdef statements. And, of course, the real code is far more complicated than this toy example.
Unfortunately (or not), I've been out of this sort of thing for a few years now, so I don't have a fresh "real" example in mind -- the above is (obviously) contrived and a bit hokey.
This, is done to make the code more readable, for later references and to make it clear, to a later reviewer, that the remaining cases handled by the last else, are do nothing cases, so that they are not overlooked somehow at first sight.
This is a good programming practice, which makes code reusable and extend-able.
I would like to add to – and partly contradict – the previous answers. While it is certainly common to use if-else if in a switch-like manner that should cover the full range of thinkable values for an expression, it is by no means guaranteed that any range of possible conditions is fully covered. The same can be said about the switch construct itself, hence the requirement to use a default clause, which catches all remaining values and can, if not otherwise required anyway, be used as an assertion safeguard.
The question itself features a good counter-example: The second condition does not relate to x at all (which is the reason why I often prefer the more flexible if-based variant over the switch-based variant). From the example it is obvious that if condition A is met, x should be set to a certain value. Should A not be met, then condition B is tested. If it is met, then x should receive another value. If neither A nor B are met, then x should remain unchanged.
Here we can see that an empty else branch should be used to comment on the programmer's intention for the reader.
On the other hand, I cannot see why there must be an else clause especially for the latest and innermost if statement. In C, there is no such thing as an 'else if'. There is only if and else. Instead, the construct should formally be indented this way (and I should have put the opening curly braces on their own lines, but I don't like that):
if (A) {
// do something
}
else {
if (B) {
// do something else (no pun intended)
}
else {
// don't do anything here
}
}
Should any standard happen to require curly braces around every branch, then it would contradict itself if it mentioned "if ... else if constructs" at the same time.
Anyone can imagine the ugliness of deeply nested if else trees, see here on a side note. Now imagine that this construct can be arbitrarily extended anywhere. Then asking for an else clause in the end, but not anywhere else, becomes absurd.
if (A) {
if (B) {
// do something
}
// you could to something here
}
else {
// or here
if (B) { // or C?
// do something else (no pun intended)
}
else {
// don't do anything here, if you don't want to
}
// what if I wanted to do something here? I need brackets for that.
}
In the end, it comes down for them to defining precisely what is meant with an "if ... else if construct"
The basic reason is probably code coverage and the implicit else: how will the code behave if the condition is not true? For genuine testing, you need some way to see that you have tested with the condition false. If every test case you have goes through the if clause, your code could have problems in the real world because of a condition that you did not test.
However, some conditions may properly be like Example 1, like on a tax return: "If the result is less than 0, enter 0." You still need to have a test where the condition is false.
Logically any test implies two branches. What do you do if it is true, and what do you do if it is false.
For those cases where either branch has no functionality, it is reasonable to add a comment about why it doesn't need to have functionality.
This may be of benefit for the next maintenance programmer to come along. They should not have to search too far to decide if the code is correct. You can kind of Prehunt the Elephant.
Personally, it helps me as it forces me to look at the else case, and evaluate it. It may be an impossible condition, in which case i may throw an exception as the contract is violated. It may be benign, in which case a comment may be enough.
Your mileage may vary.
Most the time when you just have a single if statement, it's probably one of reasons such as:
Function guard checks
Initialization option
Optional processing branch
Example
void print (char * text)
{
if (text == null) return; // guard check
printf(text);
}
But when you do if .. else if, it's probably one of reasons such as:
Dynamic switch-case
Processing fork
Handling a processing parameter
And in case your if .. else if covers all possibilities, in that case your last if (...) is not needed, you can just remove it, because at that point the only possible values are the ones covered by that condition.
Example
int absolute_value (int n)
{
if (n == 0)
{
return 0;
}
else if (n > 0)
{
return n;
}
else /* if (n < 0) */ // redundant check
{
return (n * (-1));
}
}
And in most of these reasons, it's possible something doesn't fit into any of the categories in your if .. else if, thus the need to handle them in a final else clause, handling can be done through business-level procedure, user notification, internal error mechanism, ..etc.
Example
#DEFINE SQRT_TWO 1.41421356237309504880
#DEFINE SQRT_THREE 1.73205080756887729352
#DEFINE SQRT_FIVE 2.23606797749978969641
double square_root (int n)
{
if (n > 5) return sqrt((double)n);
else if (n == 5) return SQRT_FIVE;
else if (n == 4) return 2.0;
else if (n == 3) return SQRT_THREE;
else if (n == 2) return SQRT_TWO;
else if (n == 1) return 1.0;
else if (n == 0) return 0.0;
else return sqrt(-1); // error handling
}
This final else clause is quite similar to few other things in languages such as Java and C++, such as:
default case in a switch statement
catch(...) that comes after all specific catch blocks
finally in a try-catch clause
Our software was not mission critical, yet we also decided to use this rule because of defensive programming.
We added a throw exception to the theoretically unreachable code (switch + if-else). And it saved us many times as the software failed fast e.g. when a new type has been added and we forgot to change one-or-two if-else or switch. As a bonus it made super easy to find the issue.
Well, my example involves undefined behavior, but sometimes some people try to be fancy and fails hard, take a look:
int a = 0;
bool b = true;
uint8_t* bPtr = (uint8_t*)&b;
*bPtr = 0xCC;
if(b == true)
{
a += 3;
}
else if(b == false)
{
a += 5;
}
else
{
exit(3);
}
You probably would never expect to have bool which is not true nor false, however it may happen. Personally I believe this is problem caused by person who decides to do something fancy, but additional else statement can prevent any further issues.
I'm currently working with PHP. Creating a registration form and a login form. I am just purely using if and else. No else if or anything that is unnecessary.
If user clicks submits button -> it goes to the next if statement... if username is less than than 'X' amount of characters then alert. If successful then check password length and so on.
No need for extra code such as an else if that could dismiss reliability for server load time to check all the extra code.
As this question on boolean if/else if was closed as a duplicate. As well, there are many bad answers here as it relates to safety-critical.
For a boolean, there are only two cases. In the boolean instance, following the MISRA recommendation blindly maybe bad. The code,
if ( x == FALSE ) {
// Normal action
} else if (x == TRUE ) {
// Fail safe
}
Should just be refactored to,
if ( x == FALSE ) {
// Normal action
} else {
// Fail safe
}
Adding another else increases cyclometric complexity and makes it far harder to test all branches. Some code maybe 'safety related'; Ie, not a direct control function that can cause an unsafe event. In this code, it is often better to have full testability without instrumentation.
For truly safety functional code, it might make sense to separate the cases to detect a fault in this code and have it reported. Although I think logging 'x' on the failure would handle both. For the other cases, it will make the system harder to test and could result in lower availability depending on what the second 'error handling' action is (see other answers where exit() is called).
For non-booleans, there may be ranges that are nonsensical. Ie, they maybe some analog variable going to a DAC. In these cases, the if(x > 2) a; else if(x < -2) b; else c; makes sense for cases where deadband should not have been sent, etc. However, these type of cases do not exist for a boolean.

C - Arrays. Change only specific values

I am trying to search through an array, and only check specific values (the 4th,5th and so on)- ((0+n*4) and (3+n*4).
The first one found will be checked and if it has a value of 0 will it be changed to 1 and then the program should stop. If not it will try the next value and so on..
I have the following code, but it doesn't stop ..it makes all the values 1 at once..
Any suggestions?
{
for (i=0; i<(totalnumber); i++)
{ for (n=0; n<((totalnumber)/4); n++)
{ if (i==(0+(n*4)))
{ if (array[i]==0)
{
array[i]=1;
break;
}
}
else if ((i==(3+(n*4))))
{
if (array[i]==0)
{
array[i]=1;
break;
}
}
}
}
}
Using a single break statement only breaks out of the nearest loop. It doesnt break out of the outer i loop. So, change your code to break out of the outer loop too.
One other way is to use both counter variables i,n within the same for loop. That means, you only use break once to break out of the outer for loop.
I quote from MSDN
Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control elsewhere out of the nested structure.
This is related - Can I use break to exit multiple nested for loops?

how to get out of "if" loop in c?

if(turn==2)
{
if(forward) /*then what to do if this if comes true for coming out of outer loop*/
if(columnHead>0)
{
columnHead--;
addr[columnHead] |=1<<(rowHead-1);
}
else
{
columnHead =7;
addr[columnHead] |=1<<(rowHead-1);
}
if(rowTail!=(rowHead-1))
{
addr[columnHead+columnSize] &=~(1<<rowTail);
columnSize++;
rowTail++;
}
else
{
addr[columnTail] &=~(1<<columnTail);
if(columnTail==0)columnTail=8;
columnTail--;
}
back=1;
}
I want to come out of outer if loop if it satisfies condition if(forward)
You should create function of this code, and return from the block where the condition becomes true.
A standard idiom is to use while(true){/*your code here*/ break; } around the whole block and use break statements as appropriate which will take you to the end of the while brace. Just remember to include the final break or your program will loop.
Whatever you do, don't use a goto as they are considered very poor programming style.
Some folk, from the C days where while(true) would issue a compile warning, use for(;;) instead.
The odd thing is, thinking about this some more, you could use
do {
/*your code here, using break for premature exit*/
} while (false);
which doesn't need the final break. Only I've never seen this in production code.
I guess just putting an else in there will do what you want. Also, please put braces around big blocks - it makes the else part unambiguous.
if(turn==2)
{
if(forward) {
if(columnHead>0)
{
columnHead--;
addr[columnHead] |=1<<(rowHead-1);
}
else
{
columnHead =7;
addr[columnHead] |=1<<(rowHead-1);
}
} else {
if(rowTail!=(rowHead-1))
{
addr[columnHead+columnSize] &=~(1<<rowTail);
columnSize++;
rowTail++;
}
else
{
addr[columnTail] &=~(1<<columnTail);
if(columnTail==0)columnTail=8;
columnTail--;
}
back=1;
}
}
Version after the author's comment:
if(turn==2 && !forward) {
if(rowTail!=(rowHead-1))
{
addr[columnHead+columnSize] &=~(1<<rowTail);
columnSize++;
rowTail++;
}
else
{
addr[columnTail] &=~(1<<columnTail);
if(columnTail==0)columnTail=8;
columnTail--;
}
back=1;
}
You probably have to go the other direction, that means:
You don't want to check wether
if(forward) is true, but instead you want to do if(!forward).
Though you'd need to check what type forward is. I guess it's an integer though.
You can try giving the return 0; or return something; when you need to get out of the if, before that u may want to put the entire code in a c syntax function like-
(int)someFunction(int turn, int forward,
int columnHead, int rowHead, int rowTail, int columnTail)/*have all the arguments with proper types declaration*/{
//your code with return 0;
}.
why go into the "if" in the first place.
change the outter if to:
if(turn==2 && forward) //not sure if your logic required `forward` or `!forward` you were ambiguous
{
//...
}

What does for(;;) mean?

I am confused by the for(;;) construct. I think it is a form of shorthand for an unlimited for loop but I can't be sure.
Here is the code:
for(;;)
{
//whatever statements
}
Your guess is correct; it's an infinite loop.* This is a common C idiom, although many people (including me) believe the following to be less cryptic:
while (1) { whatever statements; }
* It's infinite assuming there are no break/return/etc. statements inside the loop body.
It's an un-terminated loop. It is sometimes written with a while:
while (1)
or even better:
while (true)
I would expect to see a break or return inside any such loop, no matter whether it is written with for or while. There has to be some abnormal control flow or it really will be an infinite loop.
Yes, that's the for C syntax with blank fields for initialization expression, loop condition and increment expression.
The for statement can also use more than one value, like this sample :
for (i=0, j=100, k=1000; j < 500 || i<50 || k==5000; i++, j+=2, k*=6) {};
Maybe one step beyond in for understanding ? =)
Yes, the expressions in the for loop are just optional. if you omit them, you will get an infinite loop. The way to get out is break or exit or so.
This statement is basically equal to:
while(1) {}
There is no start, no condition and no step statement.
As I understand it, for(;;) creates a deliberate non-exiting loop. Your code is expected to exit the loop based on one or more conditions. It was once provided to me as a purer way to have a do while false loop, which was not considered good syntax. Based on the exit condition, it is easier to dispatch to a function to handle the result, failure, warning, or success, for example.
My explanation may not be the reason someone used that construct, but I'll explain in greater detail what it means to me. This construct may be someone's "Pure C" way of having a loop in which you can serially perform multiple steps, whose completion mean something like your application has performed all steps of initialization.
#define GEN_FAILURE -99
#define SUCCESS 0
/* perform_init_step1() and perform_init_step2() are dummy
place-holder functions that provide a complete example.
You could at least have one of them return non-zero
for testing. */
int perform_init_step1();
int perform_init_step2();
int perform_init_step1()
{
return 0;
}
int perform_init_step2()
{
return 0;
}
int ret_code = GEN_FAILURE;
for(;;)
{
if(SUCCESS != perform_init_step1())
{
ret_code = -1;
break;
}
if(SUCCESS != perform_init_step2())
{
ret_code = -2;
break;
}
break;
}
If part of the initialization fails, the loop bails out with a specific error code.
I arrived at using C having done a lot of firmware work, writing in assembly language. Good assembly language programmers taught me to have a single entry point and single exit. I took their advice to heart, because their creed helped them and me immensely when debugging.
Personally, I never liked the for(;;) construct, because you can have an infinite loop if you forget to break; out at the end.
Someone I worked with came up with do..until(FALSE), but the amount of proper C furvor this caused was not to be believed.
#define GEN_FAILURE -99
#define SUCCESS 0
/* perform_init_step1() and perform_init_step2() are dummy
place-holder functions that provide a complete example.
You could at least have one of them return non-zero
for testing. */
int perform_init_step1();
int perform_init_step2();
int perform_init_step1()
{
return 0;
}
int perform_init_step2()
{
return 0;
}
int ret_code = GEN_FAILURE;
do
{
if(SUCCESS != perform_init_step1())
{
ret_code = -1;
break;
}
if(SUCCESS != perform_init_step2())
{
ret_code = -2;
break;
}
}
until (FALSE);
This runs once, no matter what.

Is it possible to execute both if and else part of an if --- else control statement? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Simultaneous execution of both if and else blocks
Is it possible to put some condition, so that both if and else part in an if ...else control statement can be executed without any warning or error ??
Do not use! ;-)
Yes, by forking.
if ( fork() ) {
printf("if\n");
}
else {
printf("else\n");
}
There are no real use cases to prefer the above code, unless it is for parallel execution.
No, there's no way to write a Schrödinger if clause.
You might be able to execute both with a goto, but it would never pass a code review.
Yes, it's possible:
#include <stdio.h>
#define else if (1)
int main(void)
{
int test = 1;
if (test == 1)
{
printf("if\n");
}
else
{
printf("else\n");
}
return 0;
}
#undef else
A note for newbies: Never do this in real life! Instead, think about your problem again...
What you probably wanted is :
#include <stdio.h>
int main(void)
{
int one_condition = 1;
int other_condition = 2;
if ((one_condition == 1) || (other_condition == 2))
{
printf("if\n");
}
if ((one_condition != 1) || (other_condition == 2))
{
printf("quasi-else\n");
}
return 0;
}
You can replace the else-path by having another if-clause with negated conditions. This gives you the possibility to override it with a second condition.
No, that is not possible (inside the same process).
Maybe you've misunderstood your problem.
If you want a code block to execute regardless of the condition, take it out of the if...else statement.
void foofunc(int n)
{
a = 44*n;
if(a == 484)
{
//do something
}
else
{
//do something if a DOES NOT equal 484
}
//do something regardless of the outcome of the test.
}
In this example, ridiculous though it is, the last line is outside the condition statement, so will execute whether a == 484 or not, which seems to me to be the same as making c trigger your else block regardless of the if test succeeds.
Of course, else blocks are not mandatory, so if you don't care what happens if your condition fails, then simply don't have an else block.
void foofunc(int n)
{
a = 44*n;
if(a == 484)
{
//do something
}
//do something regardless of the outcome of the test.
}
I assume you're trying to have both branches of this sort of statement execute?
Dim X As Boolean
X = False
If X = True Then
...
Else
...
End If
You could get it to execute using GoTo ... but that goes against good programming practice.
Dim X As Boolean
X = False
If X = True Then
...
Goto ElseStuff
Else
ElseStuff:
...
End If
Instead of that you should write separate procedures / functions to accomplish the behavior you'd like to have execute in both statements ... or simply put the code which should execute in all cases outside of the If block.
That would be functionally equivalent to using the GoTo, plus it makes it clear to anybody else.

Resources