0
#include <stdio.h>
#include <conio.h>
void main ()
{
    clrscr ()   ;
    char a  [5];
    puts ("K?");
    gets (a);
    fflush (stdin);
    if (a = ("K"))
    {
        puts (a);
    }
    else
    {
        puts ("BAE");
    }
    getch ();
}

The 10th line shows an Lvalue error while compiling, please help. this is my first program ever and this is my first day ever on coding and I'm self teaching.

SandBag_1996
  • 1,570
  • 3
  • 20
  • 50
SirVirgin
  • 153
  • 1
  • 3
  • 10

3 Answers3

1
  • fflush(stdin) is Undefined Behavior
  • the comparison operator in C is a ==; = is the assignment operator. You can't assign anything to an array, so an error is thrown
  • you can compare strings using strcmp() from <string.h>; == just compares their addresses
Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
0

I think that instead of the assignment in the if statement

if (a = ("K"))

you mean a comparison.

Nevertheless arrays do not have the comparison operator. You have to compare arrays element by element yourself. For character arrays there is function strcmp declared in header <string.h>. Thus the valid code can look like

Also you should not use fflush function with standard input. Otherwise the program has undefined behaviour,

#include <string.h>

//...

if ( strcmp( a, "K" ) == 0 )
//...
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Arrays **do** have a comparison operator when they are implicitly converted into an address. – cadaniluk Apr 02 '15 at 16:44
  • @cad You are wrong. Arrays do not have the comparison operator., It is pointers that have the comparison operator., Pointers and arrays are different types. – Vlad from Moscow Apr 02 '15 at 16:45
0

There are two mistakes in this line

if (a = ("K"))

First, you are using = where you meant ==. But that is wrong anyway, you cannot test for string equality in C. It has to be something like this, which tests the first character of the string and its terminator

if (a[0] == 'K' && a[1] == '\0')

or, you can use a library function

#include <string.h>
...
if (strcmp(a, "K") == 0) {
    // are the same string.
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56