-3

While writing simple program i found strange behavior in c comparison. Here is my code:

#include <stdio.h>
#define MAXLEN 1000
 
void lowerrr(char inp[]);
//BQhiuIGEIBEIuo2jehgUIGIUGIUg3iuoOgklOIhp__rvknzioUFIU#Gnf%
int main(){
    char inp[] = "BQhiuIGEIBEIuo2jehgUIGIUGIUg3iuoOgklOIhp__rvknzioUFIU#Gnf";
    lowerrr(inp);
    printf("%s",inp);
    return 0;
}
 
 
void lowerrr(char inp[]){
    for (int i = 0; inp[i] != '\0'; ++i){
        printf("%d", ('A' <= inp[i] <= 'Z'));//always true
        //printf("%d", (inp[i] >= 'A' && inp[i] <= 'Z')); work normaly
         (inp[i] >= 'A' && inp[i] <= 'Z') ? inp[i]+= 'a' - 'A' : inp[i] ;
    }
}

I don't understand why this comparison ('A' <= inp[i] <= 'Z') always give true (and not work normally) but this (inp[i] >= 'A' && inp[i] <= 'Z') work fine? Please explain it to me.

Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40
Inc.ace
  • 37
  • 5

1 Answers1

0

C doesn't support compound conditions like, e.g., Python does. What happens here is you'll have two conditions chained from left to right. First 'A' <= inp[i] is evaluated are returns either true or false, i.e., either 0 or 1. The result of that condition is then evaluated against <= 'Z', as a you can see, both possible results of it are smaller than Z, so the entire condition will always evaluate to true.

Mureinik
  • 297,002
  • 52
  • 306
  • 350