Here is a c program.I am getting a strange output.
When num1=10 and num2=20->
#include<stdio.h>
void main()
{
int num1=10,num2=20;
clrscr();
if(num1,num2)
{
printf("TRUE");
}
else
{
printf("FALSE");
}
getch();
}
Output:
TRUE
when num1=0 and num2=220
Output:
TRUE
But when num1=0 and num2=0:
Output:
FALSE
Why does this happen?
also,what does this given below code mean:
if(num1,num2)
Thanks in advance!
You're using the comma operator. That operator first evaluates its first operand, then drops the result on the floor and proceeds to evaluate and return its second operand.
That's why your program only prints FALSE if num2 evaluates to false in a boolean context (like e.g. 0, 0.0 or NULL).
In:
if(num1,num2)
the last expression overrides all preceeding ones so it's the same as:
if(num2)
since, num2 is 0, you get FALSE.
If you check this out,
http://msdn.microsoft.com/en-us/library/2bxt6kc4(v=vs.71).aspx
the , stands for sequential evaluation, meaning the expressions are evaluated one after another, the last being your num2.
Learn about comma operator in c http://en.wikipedia.org/wiki/Comma_operator.
i=(a,b) means store b in i.
Everything else than 0 in c is true.
so if(3) if (-3) all are true
only if(0) is false
if(num1,num2)
Is a use of the comma operator. The Comma operator calculates the first operand and discards the result then the second operand and returns the result. Thus (a, b) calculates a, calculates b and then returns b.
This should clear up your confusion for the logical cases, in each of them the statement has the effect of looking at the value of b.
if(num1,num2)
is not a syntax error, but it is a logic error. Basically, this will resolve to being only
if(num2)
Only the last variable is evaluated.
I assume what you want is 'if a and b are true'. The comma like you are using means to evaluate just the last variable.
What I think you want is:
if(num1 && num2) /* num1 AND num2 */
You need to use && (logical AND) not a single & (Which is bitwise AND)
Related
Hey i am working on a code and i stuck inside this if condition which is
(Not a actual Code simplified for better understanding)
if(18&2==2)
do something;
this if condition not executing but if i write like this
if(18|2==18)
do something;
it executed normal
also when I,
printf("%d",18&2);
it gives 2 now i am so confused why the above if statement not executing,
is it because of precedence ,please explain thanks.
Yours is a precedence "error". The bit-wise operators have lower precedence than equality. Making 18 & 2 == 2 into 18 & (2 == 2), which is 18 & 1. That last one obviously evaluates to 0, since 18 is divisible by 2.
In such cases, when you get "weird results". Start by adding parenthesis to make sure every operator operates on the operand you expect it too.
The precedence of == is higher than &.
The expression:
if(18&2==2)
evaluated as follow:
2==2 result in logical true (1).
18&1 result in logical false (0);
Hence the if condition (18&2==2) evaluated as false.
I've a C university exam coming up next week and i was looking at old exam papers a one of the questions gives this fragmented bit of code.
int a=2, b=-1, c=0;
if (a-2||b&&c||a){
printf("True\n");
} else {
printf("False\n");
}
We have to determine what the output of this code will be but the if statement makes no sense to me any if statement I've come across has been very specific like saying
if( x == 0)
I don't know what this is looking for my only assumption is that its going to be always true. Am I right or is there more to it then that?
This assignment has two goals:
to show what booleans are in C: Essentially they evaluate to ints with false mapping to 0 and true mapping to 1. In turn, any numeric or pointer value can be used in an integer context, with the respective zero value (0, 0.0, NULL (pointer), 0.0f, 0L etc.) evaluating as false and all others as true.
to show the precedence of operators
&& has a higher precedence than ||, so this statement is equivalent to
a-2 || (b&&c) || a
which will evaluate to true if any of the values is true.
As a==2, a-2 is 0. c is 0, so b && c is 0 as well.
So we have 0 || 0 || a, which is true as a is 2.
Most languages interprets non-zero integers as true and zero as false, so here you would have to calculate each one of the terms. Without any parenthesis, I would suggest that the && statement is taken in account first. So we have:
if (2-2 // gives zero
|| // OR
-1 && 0 // -1 AND 0 gives false
|| // OR
a) // Which is 2, which is true
So you're right, this statement is always true. This exercice was about showing predecence orders, and the fact that everything is numerical, even in boolean logic.
This is really important for you to understand.
If the predecence was the other way around (|| > &&), you must understand that it would have been false instead. I think this example's whole point is here.
(a-2 || b) && (c || a)
false && true
--> false
You need to understand that truth and falsity in C is always numerical.
https://www.le.ac.uk/users/rjm1/cotter/page_37.htm
Namely, anything that evaluates to numerical zero is false, and anything that evaluates to numerical non-zero is true.
In c language integers 0 is treated as false and any non-zero integer value is true but it should be noted that it is language specific and the sme statement will show compilation error in java as java is more strict and integers are not converted to booleans.
Talking about the above assignment problem the expression inside if statement will evaluate to true as
(a-2||b&&c||a) is same as
(2-2||-1&&0||2) which is same as
(0||0||2) which is evaluated as
(false||false||true) and hence the entire expression evaluates to
true.
hope it helps.
int a=2, b=-1, c=0;
int first=a-2; //0 -> false
bool second= b&& c; // nonZero&&zero -> true&&false -> false
int third = 2; // nonZero -> true
// false|| false|| true -> true
if (first || second || third ){
printf("True\n");
} else {
printf("False\n");
}
you need to understand two things before solving this problem that is
operator precedence and
associativity of operators
operator precedence tells c compiler that which operation to perform first.
and if two operators have same precedence than associativity tells evaluate left to right or right to left in you expression
int a=2, b=-1, c=0;
if (a-2||b&&c||a){
you can think it as
if((a-2)||(b&&c)||a){}
means - has top precedence so it will solved first
reduced to if(0||(b&&c)||a){}
then && has higher precedence so
reduced to if(0||false||a)
then the associativity is left to right so
reduced to if(false||a)
that is(false||2)
return true
In almost every programming language as far as I know 0 means false and 1 means true.
So coming up to your question: you have used && and || operators. Both of these are called Logical operators.
Now first block of yours is a-2||b :-
2-2||-1 so 0||-1. Now since the right expression of || is -1 the or operator will return 1 i.e. True because one of the values of 0 and -1 is non-zero 0 i.e. -1.
Therefore the expression resolves to 1&&c||a :-
Now c=0, therefore 1&&0 returns a 0 because && will only return 1 if both the expressions right and left of it are non zero.
So expression becomes 0||2 :-
Now since || (or operator) requires only one of operands either on right or left side to be non zero hence 0||2 returns 1.
Now your if (a-2||b&&c||a) statement resolves to
if (1)
{
printf("True\n"); }
else......
Therefore since 1 means TRUE the if statement will execute and you will get output as True.
Please explain the output of this program:
int main()
{
int a,b,c,d;
a=10;
b=20;
c=a,b;
d=(a,b);
printf("\nC= %d",c);
printf("\nD= %d",d);
}
The output which I am getting is:
C= 10
D= 20
My doubt is what does the "," operator do here?
I compiled and ran the program using Code Blocks.
The , operator evaluates a series of expressions and returns the value of the last.
c=a,b is the same as (c=a),b. That is why c is 10
c=(a,b) will assign the result of a,b, which is 20, to c.
As Mike points out in the comments, assignment (=) has higher precedence than comma
Well, this is about operator precedence:
c=a,b
is
equivalent to
(c=a),b
The point is, the "," operator will return the second value.
Thus
c=a,b
assigns a to c and returns b
d=(a,b)
returns b and assigns it to d
The comma operator evaluates all its operands, then yields the value of the last expression.
Hey thank you very much for your time! I'm having trouble understanding the syntax of a statement in my audio coding textbook. In one example there is a print function that goes like this
printf("%d semitones up or %d semitones down\n", interval,
interval ? 12-interval : 0 );
The part I don't understand is the conditional operator, or "?". It seems like I should just read it as "if interval does not equal 0, interval = 12 - interval" but the syntax here seems strange. I'm used to the conditional operator being a more fleshed out statement, like:
a = b > c ? b : c;
"If b is bigger than c, than a = b; else a = c"
Could someone point me to any other reference for this, or explain more about this syntax? I can't find similar examples.
You're almost right, but there's no assignment taking place. It's saying "if interval is non-zero, pass 12 - interval to the printf statement, otherwise pass 0".
In general the ternary operator looks like this:
a ? b : c
Where a, b, and c are all expressions. If a evaluates to non-zero, the ternary operator evaluates as if it were b, and if a evaluates to zero, the ternary operator's result is the result of evaluating c.
Your second example is a combination of the ternary operator and the assignment operator. The ternary operator itself doesn't perform any assignments.
Any expression that results in a boolean will do. In the case of C, where integers can be used as booleans, the value 0 is considered false and anything else is considered true.
So, in your case, interval ? 12-interval : 0, means: if interval is nonzero, use 12-interval, otherwise, use 0. To be extra verbose, you could rewrite it to:
interval != 0 ? 12-interval : 0
Why does the following code run the while loop? I thought "mid = term" is an assignment, not a condition? Please explain. Thanks.
#include <stdio.h>
main ()
{
int mid = 4, term = 4;
while ( mid = term)
printf("%d\n", --term);
}
The result of an assignment is the value. Therefore the expression evaluates to 4 or a non-zero and thus, in C, TRUE.
mid = term is an expression evaluating to term. So the while loop will run till term = 0.
Because the expression evaluates to true.
Basically, you are saying mid = 4
Since any int that isn't zero, returns true in a conditional statement - the while will loop.
The expression mid = term actually evaluates to the value of mid after assignment. So, what's being evaluated is while(4). Since all nonzero integers are interpreted as true (this is kind of a simplification), the while loop will run as long as term != 0.
Both the assignment and the test happen in the "while" loop, so the printf() executes four times in this case.
Assignment are also expressions which hold a value: the value they assign. mid=0 is an expressions that evals to 0 (thus false).
You assign term to mid and then test the truth of mid. mid is truthy whenever it is non-zero. The loop terminates when term (and hence mid) has been decremented to equal 0, which is falsy.
You are assigning the value of term to mid, then the while checks the value of mid which evaluates to true, until it reaches 0.
This should output:
3
2
1
0