Working of Nested IF-Else Without the Braces - c

Can someone please explain me the working of Nested If-Else Statements written WITHOUT the Curly Braces.
I want to understand why Below Programme isn't giving me any output.
I've checked for all the 4 possibilities.
(Outer-If, Inner-If)::(True, True),(True, False),(False, True),(False, False).
I'm editing with CodeBlocks,using gcc compiler on Windows.
int main()
{
int n=0,m=0;
if ( n > 0 )
if ( m > 0 )
printf("Inner-If Condition satisfied.");
else
printf("Inner-If condition not satisfied. ");
return 0;
}
Thank You.

They work as-if there was a curly brace around the following statement. In your case then:
if ( n = 0 ){ // ToDo - did you mean `==`, `n = 0` is `0`.
if ( m = 0 ){ // ToDo - ditto.
printf("True");
} else {
printf("False");
}
}
In your case I think the bewilderment stems from your using = rather than ==.

The if-else ambiguity is solved by defining that an ambiguous else belongs to the nearest if.
The parser will see an ambiguity, however, the parser has ben adapted to solve the ambiguity as described above (e.g. yacc).
Note: the reason your program does not give any output is because n=0 (an assignment) results in n being zero and so the test becomes false, so the branch is not taken and the return is executed.

n = 0 is an assignment in C. It assigns n the value 0. Assignments also evaluate to the value that is assigned, so here, to 0, which is in a boolean context false -- so your outer if is always false.
To compare two values, use == instead, which evaluates to 1 (true) on equality, 0 (false) on inequality. *)
Your assumption about if and else was correct, the reason you don't see output is just your wrong attempt at comparing values.
A good compiler will warn you of such typos. E.g. with gcc, enable a reasonable set of warnings with -std=c11 -Wall -Wextra.
*) as a side note, in a boolean context, a zero value is false and any other value is true, so you could also write the code like this (! is logical not, inverting true and false):
if (!n)
if (!m)
// ...
Whether this is good style depends on who you ask. I personally like to write it this way if 0 semantically represents the lack of a value, or if the variable is already meant as a boolean value. Then "if not n" sounds kind of natural.

Use == inside if Statement. such as below mentioned code will work.
if ( n == 0 )
if ( m == 0 )
printf("True");
else printf("False");

Related

How would a compiler interpret `if(!(a=10))`?

I have a homework assignment in which I believe the professor has made a typo, typing if(!(a=10)) instead of if(!(a==10)). However, when asked if this was typo, she told me to "assume that the equations are correct and give your answer." Specifically, the assignment is to describe the behavior of the program:
#include <stdio.h>
int main() {
int a = 100;
while (1) {
if (!(a=10)) {
break;
}
}
return 0;
}
If the offensive code read (!(a==10)) then the program would enter the if loop, reach the break and exit both loops, which makes sense for a beginner-level course in C programming.
However, if, truly, the code is meant to read (!(a=10)) then I don't know what the compiler will interpret that to mean. I do know that the code compiles, and when you run it in UNIX, it just allows you to input whatever you want using the keyboard, like say the number "7", and then you press enter and it moves to a new line, and you can enter "dog", and move to a new line, and on and on and it never exits back to the command line. So (1) how would the compiler interpret (!(a=10))? And (2) why does the program allow you to just continue to input entries forever?
Thanks!
For the first question,
What's the meaning of if( !(a=10) ){break;},
It's equivalent to
a = 10; if(!a) {break;}
For a value of 10 !a will be 0 and it never breaks the while loop.
In this particular example, if you assign if(!(a=0)), then it will exit the loop;
For the second question, there is no code present in your example.
But first question's answer can be extended here as the loop never breaks it keeps on asking the input values.
From the C Standard (6.5.3.3 Unary arithmetic operators ΒΆ5)
5 The result of the logical negation operator ! is 0 if the value of
its operand compares unequal to 0, 1 if the value of its operand
compares equal to 0. The result has type int. The expression !E is
equivalent to (0==E).
So according to the quote the if statement
if (!(a=10)) {
is equivalent to
if ( ( a = 10 ) == 0 ) {
As the value of the assignment sub-expression, a = 10 is equal to 10 that is it is not equal to 0 then the condition of the if statement evaluates to logical false and the sub-statement of the if statement will not get the control and you will have an infinite while loop.
In fact, you can rewrite this while loop
while (1) {
if (!(a=10)) {
break;
}
}
the following way with the same effect
while ( ( a = 10 ) ) {}
or just
while ( ( a = 10 ) );
or more simply:
while ( a != 0 );
because what is important is that within the while loop the variable a does become equal to 0.
while (1) {
if (!(a=10)) {
break;
}
}
as !(a = 10) is always zero (false) it is equivalent of:
while (1) {
}

What does a ! operator mean in front of a variable?

I have just a simple question, I'm learning C programming and I know that the ! operator means logical NOT. My question is that what does it mean in this case in a do while cycle as a condition?
Is it checking somehow if the variable is changed?
I know I should probably find it somehow, but when I try to google '!'s it doesn't want to show what I meant.
#include <stdio.h>
int main() {
int input, ok=0;
do {
scanf("%d", &input);
if ( /* condition */) {
//the input is wrong it will scan another one
}
else {
//the input is correct, so the while cycle can stop
//we don't need more inputs
ok = 1;
}
} while (!ok);
//...
//...
//...
return 0;
}
!ok is the same as ok == 0.
Remember that in C, any non-zero scalar value in a Boolean context means "true" while zero means "false". It's a common C idiom to write !foo instead of foo == 0. It works for pointers as well:
FILE *foo = fopen( "some_file", "r" );
if ( !foo )
{
fprintf( stderr, "could not open some_file\n" );
return EXIT_FAILURE;
}
So, while ( x ) is the same as while ( x != 0 ), and while ( !x ) is the same as while ( x == 0 ).
Speaking loosely, the given code executes the contents of the loop repeatedly "while NOT ok", meaning "while OK is zero". In the else block, ok is set to 1, meaning that the loop will not repeat again.
More formally, !ok is an expression that is true when ok is equal to zero, and false when ok is any value other than zero.
In the context of logical operations, anything except zero (*) is true, zero is false.
so !1 is "! true" is false
!0 is "! false" is true
(*) any kind of zero: NULL counts as zero, 0.0 counts as zero
Just think about it, the ok has a Boolean value, which is false at the initialisation.
(In c, 0 has a false value, I assume that you know this.)
In the do while, it is simply negates the logical value, it still means a NOT. If the condition is true, it will loop, otherwise, won't.
If ok has a false value and you'll negate it, it will have a true value, the loop will, umm loop.
I hope you'll get the point, it does not have any other meanings.

Weird Condition Checks

Let's consider the following C code snippet.
while(!var_can_be_0_or_1 && foo_returns_0_or_1(arg1, arg2)) {
body;
}
it's a simple while condition statement which does what I am failing to understand. But let's say I have two macros
#define TRUE 1
#define FALSE 0
Can someone please tell me(or rather explain to me) what are we checking under the condition in this while loop here? I mean in what condition/s the loop body will execute and in which condition/s it will skip?
Elaboration
I found it in a book about Data Structures in a program which converts an infix expression string into a postfix one. The exact code was something like this --->
int prcd(char char);
int und, outpos;
char symb, topsymb;
while(!und && prcd(topsymb, symb)) { <----- Stuck on this one real bad
postr[outpos++] = topsymb;
popandtest(&opstk, &topsymb, &und);
}
The elaboration is probably unnecessary but just to put things into context.
;)
EDIT :
I'm really sorry if the question was somewhat unclear to people who are trying to help, so I'll explain a little bit more about what I am really asking here
Let's forget the code I wrote in the elaborate portion of this text and go back to the first one and let's just say we have a while loop , plain and simple while loop
while(!condition1 && condition2) {
execute some codes;
}
Here, condition1 = und, und is an int whose value can be either 0 or 1(and NOTHING ELSE). 0 and 1 are macroed to FALSE and TRUE respectively. And condition2 = prcd(topsymb, symb) ; it's a function whose prototype is mentioned as int prcd(char char);. Again it returns either 0 or 1 and NOTHING ELSE.
Now what I want to know is how the condition inside the while loop brackets gets evaluated.
Hope this clears things up. :)
I mean in what condition/s the loop body will execute and in which
condition/s it will skip
body will execute if var_can_be_0_or_1 is false (i.e. 0) AND the return value of the function foo_returns_0_or_1 is true (i.e. not 0).
If either criteria are not met then body will be skipped.
I am unsure if this is what you are looking for, but here is what I believe you want:
while(!var_can_be_0_or_1 && // if this is '0', continue; else exit
foo_returns_0_or_1(a, b) // if this is NOT '0', continue; else exit
Does this help?
Using your macros, this is similar to writing
while (var_can_be_0_or_1 == FALSE && foo_returns_0_or_1 == TRUE)
I say similar because, if the function foo_returns_0_or_1 does NOT return a 1, but instead returns some other number, then your TRUE macro will not match, and the condition test will fail, as written above.
C does not require you to write the equality (== TRUE), but rather can evaluate on the output of the function or the state of the variable, if it is an int, and is the better choice for this statement.
As #John Bode notes, if the first condition fails, then the second condition will never be tested. Since this is a function, then it is possible that the function will never be called.
The && operator forces left-to-right evaluation. !var_can_be_0_or_1 will be fully evaluated (and any side effects applied); if the result of the expression is non-zero (true), then foo_returns_0_or_1(arg1, arg2) will be evaluated. If the result of that expression is also non-zero (true), then the body of the loop will be executed, otherwise the loop will exit.
I think this is some pseudo code with missing pre conditions, because it won't compile as is.
if 'und' is global then it must be initialized to zero and the while loop will always be TRUE, if inside function this must be initialized with garbage because it is allocated on stack and hence the behavior is unpredictable.
Similarly, missing definition of prcd(), it is hard to suggest what it returns.
I think your need to correct the question with proper inputs.

What in the world does this statement mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this line of code mean?
I was reading an article on Opencv, and came across this:
for( i = 0; i < (faces ? faces->total : 0); i++ )
{
CvRect* r = (CvRect*)cvGetSeqElem(faces, i);
}
What in the world is this line supposed to mean:
i < (faces ? faces->total : 0)
It's the conditional operator.
The (faces ? faces->total : 0) tests faces. If it's true, then faces->total is returned and compared with i. Otherwise, if it evaluates to false, i is compared to 0.
EDIT: Per Femaref's comment, my code below (original response) is not equivalent. faces is likely modified by calling cvGetSeqElem, which in turn means that faces->total is probably modified as well. So, the condition may change in each iteration and, if faces is null (0), the loop exits.
Still, it's confusing (got me!). You could just as easily check for faces being null and exit the loop. The loop counter potentially changes in each iteration, is dependent upon the cvGetSeqElem function mutating it, and just bleh.
It is a shorthand if statement called the conditional operator. It is much the same as:
int count = 0;
if( faces )
count = faces->total;
for( i = 0; i < count; i++ ) {
CvRect* r = (CvRect*)cvGetSeqElem(faces, i);
}
So, if faces is null, count is 0 and the loop body never executes because the first test fails. Of course, you could just check first if that is null and avoid the whole thing together. That code is ugly IMO.
if( faces ) {
// do loop
}
Also, if faces->total is > 1 then you are just wasting cycles as only the last value returned by cvGetSeqElem will persist. Of course, that function could have other side effects that are being relied upon, which would make the code even more convoluted than it already is.
It's iterating up to a value that is a member in a structure.
If the structure pointer is NULL, then it iterates zero times.
It's a safety feature to prevent dereferencing a NULL pointer.
it is equivalent to
int output;
if(faces == 0)
output = 0;
else
output = faces->total;
(Note: this is just an explanation for the part in the for loop, not a replacement)
This is a trick in C. faces is in fact a pointer to a struct (visible by the -> dereferencing). There is no Boolean type in C, 0 means false, every other value is true. In this case, the pointer is implicitly cast to int and than interpreted as Boolean in the conditional operator.
The loop is terminated once the pointer to the struct is NULL. faces is changed in the cvGetSeqElem.
The ternary operator: "if faces is true, then faces->total, otherwise zero".

Conditional operator in C

can every if...then...else statement be converted into an equivalent statement using only ?:
The code:
if ( flag ) {
exit(1);
}
else {
return 0;
}
cannot be converted into:
flag ? exit(1) : return 0;
A better example - this would be inside a loop:
if ( flag ) {
continue;
}
else {
break;
}
cannot be converted to:
flag ? continue : break;
While any use I can think of for the ternary operator can be implemented as an if/else, the converse is not true; at least not without resorting to perverse and pointless 'tricks' that yield no benefit in terms of performance, readability, or maintainability.
The syntax of if/else is:
if( <boolean expression> )
<statment>|<statment block>
else
<statment>|<statment block>
whereas the syntax of the ?: ternary operator is:
<boolean expression> ? <expression> : <expression> ;
The important thing here being that an <expression> and a <statement> are different syntactic elements.
The very limited usage of the form:
if( b ) x = y else x = z ;
can be implemented as:
x = b ? y : x ;
but here the restriction is that the same variable is being assigned in both the true and false clauses, (and therefore y and z are both at least convertible to the type of x). So it may be said that any conditional assignment can be implemented with the ternary operator (after all that is its primary purpose).
Now since a function call is a valid expression, you could wrap the true and false clauses in separate functions, but to do that simply to prove a point is somewhat perverse:
if( b )
true_stuff() ;
else
false_stuff() ;
is equivalent to:
b ? true_stuff() : false_stuff() ;
and those functions can contain any code at all.
So to convert the more general if/else case to a ?: operation, the true/false statement blocks must first be wrapped in separate functions. However even then Neil Butterworth's examples will defeat this approach since the behaviour of break, continue, and return affect control flow beyond the confines of the if/else construct, (although perhaps those are also examples of code you want to avoid!). The presence of a goto in the if/else would also defeat this approach. .
I think in the end, even if you could, why would you want to?
No.
Both "branches" of the conditional expression must evaluate to the same type, and that type must not be void.
For example, you could do this:
x > 0 ? printf("Positive!\n") : 0;
because printf return int. (I would only use this in a round of code golf, though; in fact, I just did.)
But you cannot do this:
x > 0 ? exit() : 0;
because exit returns void (or, actually, doesn't return at all).

Resources