-4

I'm new to C so I found it weird when I saw this error in the line of code. Could you help me with it please?

The line which is showing the error is

if (Name == "abc") {
//full code

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char Name[8];
    puts("Enter your name here");
    scanf("%s", Name);
    if (Name == "abc") {
        puts("No, your name is abcd");
    }
    else {
        printf("Yes, your name is %s", Name);
        }
return 0;
}
not_danish
  • 19
  • 1
  • 3
    The error message tells you exactly what the problem is (you can't compare strings the way you are) and what to do to fix it (use strncmp instead). – Ken White Nov 29 '19 at 01:02
  • Welcome to StackOverflow, it is a useful resource! But...typing in code how you *want* it to work--by *guessing*--is no substitute for a [good book or tutorial](https://stackoverflow.com/q/562303/), where such basics are covered. You'll find people a bit grumpy these days when you ask for help as "why the code didn't work as you imagined it did" (in the past, the site was more forgiving, as the upvoted duplicates show!) Maybe there will be patient AI who will let you work that way, but for now with thousands of questions every hour, the human volunteers answering them can be not so patient. – HostileFork says dont trust SE Nov 29 '19 at 01:11

2 Answers2

1

The error is telling you what to do. Use strcmp instead. Here's the header file you need to include and the prototype:

#include <string.h>

int strcmp(const char *s1, const char *s2);

This function returns 0 (or false) if the two strings are equal to each other (which means they both the same length and have the same content).

This is how you would use it in your code:

if (!strcmp(Name, "abc")) {

You cannot compare strings using ==. == compares the pointers instead of the contents of the strings.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
1

The == operator doesn't work for comparing strings. What it actually does in this case is compare the starting address of the string Name with the starting address of the string literal "abc". This is what the warning is saying.

The solution, as the warning says, is to use the strcmp function.

if (strcmp(Name, "abc") == 0) {

This function returns 0 if both strings are the same, a negative value if the left operand is "greater", and a positive value if the right operand is "greater".

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
dbush
  • 205,898
  • 23
  • 218
  • 273