-1
void main()
{
int i=4,j=12;
if(i=5 && j>5)
    printf("Hi!");
else
        printf("Hello!");
}

First of all,the output of the above code is Hi!.Acording to me it should show a syntax error as i=5 is an assingment operator not i==5,if i==5 then also it is false and should print Hello,but how could it print Hi?

Maths Maniac
  • 83
  • 1
  • 7

3 Answers3

5

The condition in the if statement

if(i=5 && j>5)

is equivalent to

if( i = ( 5 && j>5 ))

As 5 is not equal to 0 and j is indeed greater than 5 then the expression ( 5 && j>5 ) evaluates to 1 and is assigned to the variable i.

From the C Standard (6.5.16 Assignment operators)

3 An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment...

So as the value of the variable i is equal to 1 then the if condition is executed.

It seems you mean

if(i==5 && j>5)
   ^^^^

Take into account that according to the C Standard the function main without parameters shall be declared like

int main( void )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

i=5 is a perfectly valid expression to put in a conditional, even if it's not a test for equality. That assignment produces a value that isn't zero, so the condition is still true.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
0

You can assign variables in condition parameters like

While((a=b)!=null){
    ...
)

Try to output every variable (i,j) to see whats going on