-3

I am new to C can anyone help me how to fix this code. I am getting a error:

'else' without a previous if

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[20];
    char str2[20];
    int value;
    printf("Enter the string: ");
    scanf("%s",str1);
    printf("Enter the string: ");
    scanf("%s",str2);
    value=strcmp(str1,str2);
    if (value==0);
    printf("The strings are same");
    else
    {
        printf("The strings are not same");
    }
    return 0;
}
IrAM
  • 1,720
  • 5
  • 18
VexZy
  • 1
  • 1
  • 1
    `if (value==0);` get rid of `;` at the end – IrAM Feb 07 '21 at 13:01
  • Please use braces for all blocks, and use correct indentation. If you stick to a [standard coding style](https://stackoverflow.com/questions/1262459/coding-standards-for-pure-c-not-c), you can avoid issues like this in future. – costaparas Feb 07 '21 at 13:10
  • Side note: [always check the return value of `scanf`](https://stackoverflow.com/questions/10084224/how-do-we-test-the-return-values-from-the-scanf-function), but you probably shouldn't be using that to read in a string in the first place.. Consider using `fgets` instead (more details in [this post](https://stackoverflow.com/questions/17294809/reading-a-line-using-scanf-not-good)). – costaparas Feb 07 '21 at 13:10

1 Answers1

2

The problem here is that the semicolon after the if statement

if (value==0);

evaluates to: if value is equal to 0, do nothing.

The following line

printf("The strings are same");

not only would get executed every time, but also breaks the if-else apart so that the following else statement does not find any related if statement.

You could use braces here instead to prevent such problems in the future.

if (value == 0) {
  printf("The strings are same");
} else {
  printf("The strings are not same");
}
Erik Wessel
  • 501
  • 3
  • 8