Which condition is true in While? - c

Sorry if this is too simple. I want to know which of the conditionals is happening exactly. Is there a way more able to capture this without repeating them inside the block with if structures? I am using C language.
while ( l < 0 || l > 2 || c < 0 || c > 2 )

You could use comma expressions, i.e. something like (expr1,expr2), which are always evaluated left to right with a sequence point at each ,; So you may rely on that expr1 is evaluated before expr2, whereas the latter serves as the comma expression's result then.
With that, the following should work, and x will bee in the range of 0..3, depending on which condition got true:
int x;
while ( (x=0,l < 0) || (++x,l > 2) || (++x,c < 0) || (++x,c > 2) )

You can assign them "on the fly" to previously declared variables:
bool ll0, lg2, cl0, cg2;
while((ll0 = l<0) || (lg2 = l>2) || (cl0 = c<0) || (cg2 = c>2)) {
if(ll0) {
// l is less than 0
} else if(lg2) {
// l is greater than 2
} else if(cl0) {
// c is less than 0
} else if(cg2) {
// c is greater than 2
}
// ...
}
Notice the if-else chain, as, since the || operator short-circuits (i.e. the second operand isn't even evaluated if the first is already true), if e.g. ll0 is true the other values aren't going to be correctly assigned.
That being said, to be honest I wouldn't bother - just repeat the conditional, if these are just integer variables these comparisons aren't going to cost you anything (actually, the compiler may even keep around the comparison value in some cases and recycle it).

You could use a loop without conditions, compute conditions in loop, and break if any of the conditions is true.
while (1) // or for(;;)
{
bool one = l < 0;
bool two = l > 2;
bool three = c < 0;
bool four = c > 2;
if (one || two || three || four) break;
// bool variables are available there
}
If you want to get access to all conditions, you cannot use short-circuiting evaluation for them. So make sure you really want to store them beforehand.

Related

How is 0 used in conditional operator in C?

Conditional operator in C is used like this:
condition ? value_if_true : value_if_false
What does 0 mean when it's used in the value_if_false?
I've seen some people using it like this, for example.
a == b ? i++ : 0
It seems like it does nothing. Does this work like return 0 in other functions?
In C language, ternary is shorter version of if statement and it requires both statements, if_true and if_false. It would be like this (in fact it can have multiple statements for one case, separated with comma):
Short:
condition ? if_true : if_false;
Long:
if (condition) {
if_true;
} else {
if_false;
}
You can also assign the value if you put something infront of condition.
Short:
result = condition ? if_true : if_false;
Long:
if (condition) {
result = if_true;
} else {
result = if_false;
}
Now here is the trick. In C language, writing 0; is a valid statement, so your ternary becomes in longer version same as code below:
if (a == b) {
i++;
} else {
0; /* This is valid C statement */
}
Or if you have assignment too, it would be:
if (a == b) {
result = i++;
} else {
result = 0;
}
You can also do this:
int a;
/* Code here ... */
condition ? a = 5: 0;
That is effectively the same as:
if (condition) {
a = 5;
} else {
/* DO not touch a */
}
The ?: operator is a ternary operator, but it is not called "ternary" as some answers and/or comments here suggest. It just is the arity of the operator, just as + is a binary operator or as & is unary. If it has a name at all, it is called "Conditional Expression"-operator
It is not quite equivalent to if/else, because it is a conditional value (with the consequence, that both expressions must have the same type) in the first place, not a conditional execution. Of course, both types can be cast to make them equal.
In the case of what the OP does, a better option (if if shall not be used) is in my opinion:
a == b && i++;
which resembles a bit more logical what happens. But of course it is a matter of style.
The reason why someone might want to write a == b ? i++ : 0; is that s/he probably wants to have an (Caution! You are now entering an opinion-based area) easier and faster alternative to if (a == b) i++; - although this is of course opinion-based and I personally not share the same opinion.
One thing I can think of as a "blocker" at the if statement is the requirement to write the parentheses () which can be omitted by using the conditional operator instead.
"But why the 0?"
The C syntax requires a third operand for the conditional operator. Else if you would want to compile for example:
a == b ? i++;
you will get an error from the compiler:
"error: expected ':' before ';' token"
Or respectively, doing so:
a == b ? i++ : ;
would raise:
"error: expected expression before ';' token"
So they use 0 as kind of "syntax satisfier" to be able to use the conditional operator as replacement for the if statement. You could use any other numeral value here as well, but 0 is the most readable value, which signifies that it has no use otherwise.
To showcase the use at an example:
#include <stdio.h>
int main (void)
{
int a, b, c = 4;
a = 2;
b = 2;
a == b ? c++ : 0;
printf("%d",c);
return 0;
}
The output for c will be 5, because a == b.
Note that a == b ? i++ : 0 is different when used f.e. inside of an assignment like f.e.:
int c = a == b ? i++ : 0;
Here c is either getting assigned by i or 0, dependent upon a == b is true or not. If a == b is true, c is assigned by i. If a == b is wrong, c is assigned by 0.
Side Notes:
To view it from a technical point, ?= is called the "conditional operator". The conditional operator is one of the group of ternary operators.
If you want to learn more about the conditional operator ?=, look at ISO:IEC 9899:2018 (C18), ยง6.5.15 - "Conditional operator" for more information.
There's nothing special about 0 one could write
a == b ? i++ : 1
And it would behave the same way.
Only difference is when you assign the expression to say another variable:
int c = a == b ? i++ : 1;
// a == b -> c will be i++
// a != b -> c will be 1
However it's much cleaner to write
if (a == b) i++;
It helps to think of the ternary operator as a shorthand way or writing an if-else statement.
If(a == b){
i++;
}else{
//if assigned, return 0. Else do nothing.
}

Working of Nested IF-Else Without the Braces

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");

zero is greater than or equal to zero evaluates to false

i = 0;
if(0 <= i <= 0)
this returns false.
I don't understand this at all. Watch window I also tried making the statement read (0 <= i && i <= 0) when I test them individually 0 <= i returns false while i <= 0 returns true. they both should be true. I'm not sure if this is a precision thing but I wouldn't think so since I'm hard coding the values in. Please help me understand this fundamental problem.
If it helps I am trying to evaluate if a point is on a line by getting the intersection point and then checking if it's between the x and y start point and end point. this becomes a problem when I am trying to check when x or y is on its axis then you run into the problem of checking if 0 is between or equal to 0 and 0. Which it is so it would fall on the line.
Chaining of relational operators is not possible (to produce a valid result as per the expectation), you need to write separate instruction to verify each condition.
Due to the absence of explicit parenthesis and LTR association, a statement like
if(0 <= i <= 0)
is evaluated as
if( (0 <= i) <= 0)
which boils down to
if ( 1 <= 0)
which produces a 0, (FALSE).
That said, the claim pertaining to
I also tried making the statement read (0 <= i && i <= 0) when I test them individually 0 <= i returns false while i <= 0 returns true. they both should be true
is not correct, they both are true. See for yourself

For-Loop and Arrays Java

Can anyone explain to me in words what the code after 'for' exactly means? I'm confused with the mixing of int and booleans within 'for' (still a beginner). It's about checking whether two arrays have the same values in the same sequence. Thanks in advance:
public static boolean equal(int[] a1, int[] a2) {
if (a1.length != a2.length) {
return false;
} boolean equal = true;
for (int i = 0; i < a1.length && equal; i++) {
equal &= a1[i] == a2[i];
}
return equal;
}
The for loop consists of 4 parts:
for(initialisation; condition; increment/decrement) {
body
}
Where initialisation is the part where you initialise variables which are in scope throughout the loop.
Condition is the boolean expression which if evaluated to true results in the execution of the body.
Increment/decrement is where you may change the value of any variable in the loop scope.
All 3 parts after the for keyword are optional, so you could create an infinite loop as shown:
for(;;) {
System.out.println("body");
}
The line equal &= a1[i] == a2[i]; is using the &= (logical-and assignment) operator, which is the same as equal = equal & (a1[i] == a2[i]);. It combines the logical-and with the assignment operator. This line can be parsed like this:
bool = (itself) AND (int == int)
bool = (itself) AND (another bool)
bool = (some bool value)
Be very careful with the & operator, since it has two different meanings. It means logical-AND for boolean types, but bitwise-AND for numeric types. To make it clearer to read, use equal = equal && a1[i] == a2[i]; which also has the upside of short-circuit operation (which can save a few unnecessary comparisons).
On another note, there are a few redundancies in this loop.
boolean equal = true;
for (int i = 0; i < a1.length && equal; i++) {
equal &= a1[i] == a2[i];
}
The looping condition checks that the array still has elements AND that the previous element(s) have all matched. Since the looping condition is also checking the boolean equal, there is no need to use the compound and-assignment operator. A simple equal = a1[i] == a2[i]; would work and even save the unnecessary (true) & (something) operation every loop iteration. This works because the looping condition guarantees that equal == true, since the loop will stop execution otherwise.

if-else condition in C

In C language, what is the result of x=0 if I put it in if-else condition? if it is represent false or if this assignment is finished, then represent true?
my colleague write code as:
if(condition = 0)
{
//do process A
}
else
{
// do process B
}
obviously, this code is wrong, I know it should be condition == 0 or ((condition=foo()) == 0) but my assumption is program should always do process A because i think if(condition = 0) should always return true since this is set value 0 to variable condition and this set process should be true. However, program always do process B, that means if use the variable condition value and my assumption is wrong.
Then I did a another test code:
if(condition = 2) //or other none-zero value
{
//do process A
}
else
{
// do process B
}
this time, program always do process A.
My question is why if-else condition does not use the operation value of condition but use the left variable after setting?
when you assign 0 to variable condition it becomes false as 0 represents false and any non-zero value represents true.so, when you assign 0 else condition is executed and when you assign 2 condition represents a true statement so, it executes...
if(condition = 0)
after assigning value 0 to condition it becomes
if(condition)
and as it is false, it doesn't execute.but, when condition = 2, it works in the same way and become true .so, the if condition is executed then.
You use wrong operator.
a = 10;
The "equals" operator means "assign value to".
Now to compare two operands, a and b, to see if a = b, you use another operand.
That operand is double equals (==).
if(variable == 0)
{
//do process A
}
else
{
// do process B
}
Now look.
If the variable with name "variable" has value = 8 that is not equal to 0,
thus the whole "variable == 0" expression if FALSE.
So proccess B will run.
If otherwise variable is equal to 0 indeed, proccess A will be executed because "variable == 0" is true.
It's like:
if(EXPRESSION)
{
// EXPRESSION IS TRUE
}
else
{
//EXPRESSION IS FALSE
}
Got it? :)
In C, assignment is an expression that returns the set value; i.e. x = 2 will result in 2.
This allows you to do something like this:
unsigned char ch;
while((ch = readFromFile(f)) != EOF) {
// do something with ch
}
It also allows you to shoot yourself in the foot if you accidentally mistype == as =, which is why this 'feature' doesn't appear in a lot of other languages.
In your first loop, the expression condition = 0 will always result in 0, causing the else branch to be taken. Similarly, condition = 2 results in 2, which causes the true branch to be taken.

Resources