0

I am currently a beginner learning C and come across a statement from Stackoverflow (link), that C associate this operator (<) from left to right.

What i conclude from the answer is that, C is just gonna run it left to right one by one instead of what human perceive as (a<b<c), but i also assume that if two operators has the same Associativity, C is also gonna run it from left to right, is this correct?.

The second part is, if (a<b<c) is actually written ((a<b) && (b<c)) wouldn't it be more efficient to write a code like this:

#include <stdio.h>

int x = 7 ;

int main() {
   
   if (x > 20)
   {
     printf("y");
   }
   else 
   {
       if (x == 7) 
       {
           printf("n");
       }
       else if (x > 7)
       {
            printf("z");
       }
       else 
       {
           printf("h");
       }
   }
    
    return 0;
}

rather than this:

#include <stdio.h>


int x = 7;

int main() {
   
   if (7 < x && x <= 20)
   {
     printf("z");
   }
   else if (x > 20)
   {
        printf("y");
   }
   else if (x == 7)
   {
         printf("n");
   }
   else {
        printf("h");
   }
    
    return 0;
}

Because the 2nd code does more comparison operation than the 1st one,is this true?.

1 Answers1

0

In C, && short-circuits. That means the right-hand side is not evaluated if the left-hand side is false. Similarly for || and a left-hand side that's true. In both cases the right-hand side does not influence the outcome.

This is important in code like if (p && p->q) where the pointer p is dereferenced only if it's not NULL.

Having said that, the performance of such comparisons is virtually instant. They map pretty directly to CPU instructions, unlike printf. Your code's speed will be limited by that printing.

MSalters
  • 173,980
  • 10
  • 155
  • 350