Alex RD Alex RD - 1 year ago 132
C Question

Char comparison on if statement doesn't evaluate to true

Why doesn't the following IF statement evaluate to true, even though sex[i] has the value of M char?

for (i=0;i<3;i++)
if (sex[i] == 'M' || sex[i] == 'm')

What i'm trying to do, is create an array of characters that holds several values for strings or characters. In this case, it's a character and it works outside the if function, if i print sex[0] i get M.

Oh, and i know that the variable needs to be declared like this

char sex[size][sizeofstring]

The entire code:

#include <stdio.h>

int main() {
char name[10][256], sex[10][256];
int i;
for (i=0;i<3;i++) {
printf ("Insert the name of the person %d and her gender, M for male F for female\n", i+1);
scanf("%s", name[i]);
scanf(" %c", sex[i]);
for (i=0;i<3;i++)
if (*sex[i] == 'M' || *sex[i] == 'm')
printf ("\n%s", name[i]);
for (i=0;i<3;i++)
if (sex[i] == 'F' || sex[i] == 'f')
printf ("\n%s", name[i]);

Answer Source

Given the declaration

char sex[size][sizeofstring];

use of

if (sex[i] == 'M' || sex[i] == 'm')

does not work since it becomes a pointer comparison operation. It is equivalent to:

char* p = sex[i];
void* p1 = 78;   // Assuming ASCII encoding.
                 // 'M' is an int. The int is converted to a pointer.
void* p2 = 102;  // Again, assuming ASCII encoding
if ( p == p1 || p == p2 )

That explains why the conditional in the if statement never evaluates to true.


You should use:

if ( strcmp(sex[i], "M") == 0 || strcmp(sex[i], "m") == 0)

If your compiler supports the non-standard case insensitive string comparison function, stricmp, you can combine the two tests.

if ( stricmp(sex[i], "M") == 0 )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download