+ 2
Getting weird Output in C which I have no explanation to.
Hey. guys... I got a really strange result while trying to compare "A" with "a" in C. When I am comparing with single quotes 'a' >'A' , it is displaying True(1)..which should be the proper output actually, but is I'm comparing it with double quotes as a string, its showing False(0)... Can somebody explain this?😵 Here's the code below 👇 #include <stdio.h> //Compiler version gcc 6.3.0 int main() {int a = "a" > "A"; printf("%d",a); return 0; }
5 ответов
+ 7
Strings literals are pointers of type const char*, so by comparing them you actually compare their memory adresses, which will not be the same since they are two different pointers to two different literals, hence false is returned. To properly compare strings in C, strcmp() should be used:
https://en.cppreference.com/w/c/string/byte/strcmp
+ 4
It should return false as well, but not necessarily due to the memory reservation, I think it's a little more complex than that and goes into the undefined behaviour/unspecified behaviour realm. I have never concerned myself with comparing pointers with operators other than == and !=, but maybe the following threads can help you:
https://stackoverflow.com/questions/44397784/is-operator-less-than-on-pointers-consistent
https://stackoverflow.com/questions/4607418/how-do-the-operators-and-work-with-pointers/4607440#4607440
+ 2
Shadow Ooooooo..... thanks I get it!
+ 2
Shadow So if I compare "A" < "a" this time also it will return false right? Because memory for "A" is getting reserved first and then for "a" ?..
+ 1
Shadow I checked it out.. really weird....thanks for your help.