Search code examples
cansi-c

Single line statements


#include<stdio.h>
#include<stdlib.h>

int main()
{   
    int i,max,max2;     

    int arr[10];
    for(i=0;i<10;i++)   arr[i]=rand()%101;

    for(i=0;i<10;i++)   printf("%d\n",arr[i]);

    max=arr[0]; 
    for(i=0;i<10;i++)
    {
        if(max < arr[i])    max2=max;   max=arr[i];

    }
    printf("Max is : %d\n",max);
    printf("2nd max is : %d",max2);
}

Output : 32 32 54 12 52 56 8 30 44 94

Max is : 94

2nd max is : 44

But when I change my 'if' statement to

if(max < arr[i])
    {   
        max2=max;
        max=arr[i];
    }

It works fine !

Max is : 94

2nd max is : 56

I've previously used more than one operation in a single line statement like

if(xyz) doSomething; break;

But it doesn't work here, why?


Solution

  • There is no such thing as "single line statement" in C, as C does not care about new-lines. They are used only to help the reader read.

    This

    if(max < arr[i])    max2=max;   max=arr[i];
    

    is equivalent to

    if(max < arr[i])    
      max2=max;   
    max=arr[i];
    

    is equivalent to

    if(max < arr[i])    
    {
      max2=max;   
    }
    max=arr[i];