Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "a" != "a" in C?

Tags:

c

string

void main() {     if("a" == "a")       printf("Yes, equal");       else       printf("No, not equal"); } 

Why is the output No, not equal?

like image 288
Javed Akram Avatar asked Jan 30 '11 15:01

Javed Akram


People also ask

How to see if 2 strings are equal in C?

C strcmp() The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

How to do string comparison in C?

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.

What does &= mean in C?

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.

What does string compare return in C?

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.


1 Answers

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 
like image 125
Tim Cooper Avatar answered Oct 12 '22 23:10

Tim Cooper