You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在C语言中不能使用==运算符比较字符串变量?

Why == Fails When Comparing Your C String Arrays

Hey there! Let's break down exactly why your equality check isn't working like you expect. I've run into this exact gotcha plenty of times when starting out with C, so I get the confusion.

What == Actually Does Here

In C, when you use an array name like name1 or name2 in an expression (like the == check), it decays into a pointer pointing to the first element of the array. So when you write name1 == name2, you're not comparing the actual text "John" vs "John" — you're comparing the memory addresses where these two arrays are stored.

Why Your Specific Code Fails

Your code declares two separate character arrays:

char name1[] = "John";
char name2[] = "John";

Even though their content is identical, these are two distinct blocks of memory. name1 lives at one address in RAM, name2 lives at another. Since their pointers point to different locations, name1 == name2 evaluates to false, so your printf never runs.

The Correct Way to Compare String Content

To check if two strings have the same characters, you need to use the strcmp() function from the standard library. It's designed specifically for comparing string contents character by character.

Here's how to fix your code:

#include <stdio.h>
#include <string.h> // Need this for strcmp()

int main() {
    char name1[] = "John";
    char name2[] = "John";
    
    if (strcmp(name1, name2) == 0) { // strcmp returns 0 when strings are equal
        printf("Same!");
    }
    return 0;
}

A quick note on strcmp() return values:

  • Returns 0 if the strings are identical
  • Returns a negative number if the first string is "less than" the second (lexicographically)
  • Returns a positive number if the first string is "greater than" the second

A Quick Side Note: String Literals vs Arrays

Just to avoid future confusion: if you'd declared your variables as pointers to string literals like this:

char *name1 = "John";
char *name2 = "John";

You might actually see name1 == name2 evaluate to true. This is because many compilers optimize duplicate string literals to point to the same memory address. But this is not guaranteed behavior — it depends on the compiler and its settings. Never rely on this for string comparison; always use strcmp() for consistent results.

内容的提问来源于stack exchange,提问作者Crossunit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:59:06