Simon_A Simon_A - 3 months ago 17
C Question

Simple check for character in char array in C

I am new to C. This code runs on a Flyport module and compiles on their own IDE but I should think my error should be easy to spot for anyone familiar with C.

I can't get this code to compile despite changing almost everything, what am I doing wrong?

char string_serial[50]="starting Value";

if (string_serial[0] = "*")
{

UARTWrite(2,"First Char OK");
UARTWrite(2,"\r\n");

else

UARTWrite(2,"First Char NOT OK");
UARTWrite(2,"\r\n");

}


If it's not obvious I am trying to check if character 0 in the array is *.

Thanks

Answer

The syntax for if/else conditions is wrong

The syntax should be

 if(condition)
  {
  }

  else
  {
  }

For your specific code it should be

if (string_serial[0] == '*')
        {   

            UARTWrite(2,"First Char OK");
            UARTWrite(2,"\r\n");
         }

else 
        {
            UARTWrite(2,"First Char NOT OK");
            UARTWrite(2,"\r\n");

        }

The = operator is assignment, it assigns the value (returning true when successful). What you need is == (for comparing).

Also use single quotes for characters as shown in the code above.