Thursday, October 29, 2009

Assigning value in if instead of condition

We know that if is used to check condition the general syntax for if conditional statement is

if(condition)
{
Statement1;
}
else
{
Statement2;
}

But we can assign the value for the variable in if and also it work as condition checking.
Here’s the sample program to implement that;

#include < stdio.h >
void main()
{
int i=0,j=0;
if(i=1)
{
j++;
}
printf(“%d %d “, i , j);
}


In this program initially i=0 and j=0.
In if i was assigned i=1 instead of condition checking.
Now i=1 and now the 1 will be act as condition in if. (1 is true, 0 is false).
So condition is true so j will be increased now j=1.
Output:
1 1

If you give i=0 in if i.e.,
if(i=0)
0(false) so j won’t be increased
Output:
0 0

Note: it’ll show only warning as “possibly incorrect assignment” s . Don’t care about that . you can do this in loops

0 comments:

Post a Comment