void main() { if("a" == "a") printf("Yes, equal"); else printf("No, not equal"); }
Why is the output No, not equal
?
C strcmp() The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
We take the user input as strings. We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
It means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form.
In the C Programming Language, the strcmp function returns a negative, zero, or positive integer depending on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2.
What you are comparing are the two memory addresses for the different strings, which are stored in different locations. Doing so essentially looks like this:
if(0x00403064 == 0x002D316A) // Two memory locations { printf("Yes, equal"); }
Use the following code to compare two string values:
#include <string.h> ... if(strcmp("a", "a") == 0) { // Equal }
Additionally, "a" == "a"
may indeed return true, depending on your compiler, which may combine equal strings at compile time into one to save space.
When you're comparing two character values (which are not pointers), it is a numeric comparison. For example:
'a' == 'a' // always true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With