what if I use many 'if's and only one 'else' [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
stackoverflow friends, I have been studying C language in college.
While stuyding, I become curious about that there is a technical error if I use many if struct and only one else.
For example:
if (condition 1)
if (condition 2)
if (condition 3)
if (condition 4)
else
In the above case, I worry about if the variable that doesn't match the condition of first if struct,
it would go "directly" to else, not to the second if.
Is my worrying true? or It will never happen?
Thank you in advance.

Per C11 Standard draft 6.8.4.1p3:
An else is associated with the lexically nearest preceding if that is
allowed by the syntax.
That is in the nested if structure it will correspond to the innermost if ("if (condition 4)").

If you want to chek each condition in turn uintil a match is found, use
if (condition 1) {
} else if (condition 2) {
} else if (condition 3) {
} else if (condition 4) {
} else {
}
this is really the same thing as:
if (condition 1) {
} else {
if (condition 2) {
} else {
if (condition 3) {
} else {
if (condition 4) {
} else {
}
}
}
}

Related

How should I arrange my if...else if in C? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
My school teacher teaches if...else if today. She teaches us to write the if...else if like this
if(x == 1) {
//some code here
}
else if(x == 2) {
//some code here
}
else if(x == 3) {
//some code here
}
else if (x == 4) {
//some code here
}
But, from what I learn from Internet is mostly write like this
if(x == 1) {
//some code here
}
else if(x == 2) {
//some code here
}
else if(x == 3) {
//some code here
}
else if (x == 4) {
//some code here
}
So, my question is which should I follow? Internet or my teacher ? I never seen anybody write if...else if like my teacher before.
p.s. I know these two will give same result when running it. Just confusing how should I arrange the if...else if statement.
I normally don't like style debates, but your teacher chose a really strange style indeed.
You are correct, almost everybody writes else if like in your second example, even when the local standard calls for never using single statement blocks with curly braces omitted, as though else if were a keyword with a space in it.
I have seen people ban it, but everybody else who does so always ends up with
else {
if () {
}
}
or a variant of it where one or more opening braces go on their own lines.
We should remember that else if ladders get very long indeed and a style that requires indenting them becomes intolerable after while. Most languages that have more rigid whitespace rules (I'm looking at you Visual Basic) end up with an elseif keyword to avoid this problem.

Easy C Program While loop Not Working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
hey im lost on why this loop doesnt work it all seems right but nothing inside the while works please help the rest of the code is in other files if you need them i can post them
#include <stdio.h>
#include "weatherstation.h"
int dunits = METRIC;
void main(void)
{
char test;
InitializeWeatherStation();
while(1);
{
UpdateWeatherStation();
printf("Enter m for Metric units, b for British units, or q to quit");
scanf_s("%c",&test);
if(test == 'm')
{
dunits = METRIC;
}
else if(test == 'b')
{
dunits = BRITISH;
}
else if(test == 'q')
{
return;
}
DisplayWeatherData(dunits);
}
}
while(1);
{
something;
}
is exactly the same as:
while(1)
{
}
{
something;
}
In other words, what you have there is an infinite loop followed by a scoped block of code (which will never be reached).
Get rid of the semicolon and it should fix that particular problem.
You must not end the while(1) with a semi-colon dude. Because that's a null statement you wrote in there.

strcmp does not stop when typing 'yes' command [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I've made this joke program with string compare, but when I type "yes" it also types what I have for the else statement. It doesn't do this when I type "no", and responds predictably if I type something other than "yes" or "no".
#include<stdio.h>
#include<string.h>
int main ()
{
char ansr[50];
printf("Are you a cop?");
scanf("%s", &ansr);
if (strcmp(ansr, "yes") == 0)
{
printf("Then get outta here buddy!");
}
if (strcmp(ansr, "no") == 0)
{
printf("Then you can learn the secret handshake!");
}
else
printf("\nDude! Yes or no question! Are you a cop?!\n");
}
There are a few things to notice. First, you never use scanf to read anything into ansr before using it, which leads to undefined behavior. Second, as others have said, your if/else statements are not congruent. Third, you need a while loop to ask the question again if the answer is invalid. You could rearrange it like so:
int main ()
{
char ansr[50];
printf("Are you a cop?\n");
scanf("%49s", ansr);
while (strcmp(ansr, "yes") && strcmp(ansr, "no"))
{
printf("\nDude! Yes or no question! Are you a cop?!\n");
scanf("%49s", ansr);
}
if (strcmp(ansr, "yes") == 0)
{
printf("Then get outta here buddy!\n");
}
else
{
printf("Then you can learn the secret handshake!\n");
}
return 0;
}
ansrstays uninitialised, before touching it via strcmp(), the latter invokes the infamous Undefined Behavior, anything can happen.
Your code has a if block and an if else block. So it compares ansr twice, change it to if else if block, it will only check once.
#include<stdio.h>
#include<string.h>
int main ()
{
char ansr[50];
printf("Are you a cop?");
//should take input here
if (strcmp(ansr, "yes") == 0)
{
printf("Then get outta here buddy!");
}
else if (strcmp(ansr, "no") == 0)
{
printf("Then you can learn the secret handshake!");
}
else printf("\nDude! Yes or no question! Are you a cop?!\n");
return 0;
}
Edit : Removed some words as suggested. Sorry, included them from op code.

break statement doesn't work in a loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I saw a tutorial that explaining how to use the "break" statement in a loop
but every time i'm trying to use it i'm getting a compilation error saying:
"break statement not within loop or switch
break;"
This is my code:
if (finalFirstChar > 6 || finalFirstChar < 1)
{
printf("You didn't entered a proper number! \n");
break;
}
FWIW, if is a condition (selection statement, to be exact), and break works in a loop (iteration statement)/switch-case statement.
As per C11, chapter §6.8.6.3
A break statement shall appear only in or as a switch body or loop body.
In any case, you don't need a break in a if statement body.
OK:
while (cond1) {
if (cond2) break; /* or continue; */
if (cond3) return [something];
}
for (init; cond4; after) {
if (cond5) break; /* or continue; */
if (cond6) return [something];
}
do {
if (cond7) break; /* or continue; */
if (cond8) return [something];
} while (cond9);
if (cond10) return [something];
NOT OK:
if (cond11) { /* not in any while/do/for loop, or case switch */
break; /* or continue; */
}

Chain of OR conditions in if statement [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In my code I have a if statement, which looks like:
if(someFunction1(a) || someFunction2(b->b1,c) || *d == null || somefunction3(e) > f * g || !e->e1 || ...){
return 0;
} else {
do_something;
}
In my code with real variable and function names are conditions nearly in three lines and it looks very overlook. So I decided to rewrite it into form:
if(someFunction1(a)){
return 0;
} else if(someFunction2(b->b1,c)){
return 0;
} else if(*d == null){
return 0;
} else if(somefunction3(e) > f * g){
return 0;
} else if(!e->e1){
return 0;
} else if(...){
return 0;
} else{
do_something;
}
Is there any argument why I should not do it?
From a purely semantic-syntactical point of view there's no effective difference between them. But if readability is your concern, why don't you use the "datenwolf" formatting style – I came to develop that style over the course of my past 5 projects or so:
if( someFunction1(a)
|| someFunction2(b->b1,c)
|| *d == null
|| somefunction3(e) > f * g
|| !e->e1
|| ...
){
return 0;
} else {
do_something;
}
Do you see how beautiful everything lines up? It really looks like a tube the program is falling down through until it hits a met condition. And if you have && it looks like a chain of operations that must not be broken.
As you're asking because of readability you may want to rearrange the long conditional into predicate variables that say why zero must get returned.
bool unnecessary = someFunction1(a) || someFunction2(b->b1,c);
bool beyondTolerance = somefunction3(e) > f * g;
bool invalidInput = *d == nullptr || !e->e1;
if (unnecessary || beyondTolerance || invalidInput)
return 0;
else
...
This is Martin Fowler's Decompose Conditional refactoring.
Option 1:
Terseness
One exit point to avoid redundancy of return statement.
Option 2:
Exact failure point can be diagnosed easily i.e logs can be added to each branch to detect the failure.
I don't think there is any other problem in this code other than the redundancy involved. If at all you have to make change to the return statement, you have to change it at 6 places,according to your implementation.
But that redundancy does not occur in the first implementation.
Both are similar otherwise.
First of all, you can't answer this question without providing some rationale, or the answer will become completely subjective. I would be wary of people answering "do like this, because I like this best", with no rationale provided.
Looking at the code, it is obviously a number of error checks done inside a function. In a real code example, all such error handling usually requires plenty of comments, to describe each individual error condition, as functions with extensive error handling tend to be complex.
Given that, it is not a good idea to write the code as one statement at all, because if you have to squeeze in comments in the middle of the statement, the code will become a mess.
With the above rationale, the best way to write such is perhaps:
/* comments here */
if(someFunction1(a)){
return 0;
}
/* comments here */
if(someFunction2(b->b1,c)){
return 0;
}
...
/* if we got here, then there are no errors */
do_something();
This also have the advantage of being maintainable, should you need to execute code in between the error checks. Or if you wish to split some of the more complex expressions into several lines for readability.
Even though there are plenty of cases where multiple return statements have the potential to create messy code, this is not one of them. In for this case, multiple return statements actually improve readability/maintainability. You shouldn't dogmatically avoid multiple return statements just because some coding standard tells you to do so.
You can do it the following way
int not_valid = someFunction1(a) ||
someFunction2(b->b1,c) ||
*d == null ||
somefunction3(e) > f * g ||
!e->e1 || ...;
if ( !not_valid )
{
do_something;
}
return !not_valid;
Instead of not_valid you can select a more appropriate name.:)

Resources