user7689951
user7689951

Reputation:

c how to check the first char of an array

I am trying to take in 10 characters over a serial console and add them to an array called buffer. The first character needs to be 'L' or 'S' and the next characters either '1' or '0'.

The code passes the first if statement ok. But the line if((buffer[0] != 'L') || (buffer[0] != 'S')) doesn't seem to work even when I enter 'L' OR 'S'.

Is there anything wrong with using the buffer[0] != notation?

int main(void)
{
char ch;
char buffer[10] = "";

putstring("Enter 9 characters beginning with 'L' or 'S' and 8 digits\r\n");

for (int i = 0; i < 9; i++) {

    ch = getcharacter();

    if ((ch == '0') || (ch == '1') || (ch == 'L') || (ch == 'S')) {

        buffer[i] = ch;
        //check first character
        if((buffer[0] != 'L') || (buffer[0] != 'S')) {

            printf("First letter must be L or S\r\n");
            goto error;
        }
        error:
        return -1;
    }
}
}

int getcharacter(void) {

char c = 0;
const uint32_t recieve_ready = 1 << 7;

//disable interrupt for a read ready
*uart_control_reg = 0;

while (1) {
    //check if RRDY bit is set
    if ((*uart_status_reg) & recieve_ready) {
        c = *uart_rxdata_reg;
        break;
    }
}
return ((char) c);

}

Upvotes: 1

Views: 1403

Answers (2)

JeremyP
JeremyP

Reputation: 86651

if((buffer[0] != 'L') || (buffer[0] != 'S'))

is wrong, you need

if((buffer[0] != 'L') && (buffer[0] != 'S'))

or

if (!(buffer[0] == 'L' || buffer[0] == 'S'))

Your original code was "if the char is not L or the char is not S" which is always true. If the char is L, then the second part was true, making the whole if statement true.

Just noticed Chris Turner's comment above. The return -1 is always executed, move it to replace the line that says goto error.

Upvotes: 7

Antoni Maniscalco
Antoni Maniscalco

Reputation: 453

Try using

if((buffer[0] != 'L') && (buffer[0] != 'S'))

instead of

if((buffer[0] != 'L') || (buffer[0] != 'S'))

Just some logic problem here. According to your code, the char needs to be equal to 'L' AND 'S' to avoid the condition, which is never the case !

Upvotes: 5

Related Questions