Home > Software design >  Why if else statements are not working for an array?
Why if else statements are not working for an array?

Time:11-17

#include <stdio.h>

int main() {
    char array[2][2] = {"-", " "};
    printf("%s", array[0]);
    
    if(array[0] == "-"){
        printf("Its a minus/n");
    }
    else{
        printf("\nNothing");
    }
    
    return 0;
}

Every time I run the code, only else gets executed. I have explicitly mentioned that if 0th index of array is equal to a string minus then print its a minus.

I have declared char array[2][2] character array. Stored only one element in it regardless of limit being of 2 elements. And I am calling array[0] because I want only first character.


if(array[0] == "-"){
    printf("Its a minus/n");
}
else{
    printf("\nNothing");
}

Does anyone has a solution for it?

CodePudding user response:

== does not compare strings.

use strcmp for that.

if(!strcmp(array[0], "-") 
{
 /* ... */
}

CodePudding user response:

In the expression of the if statement

if(array[0] == "-"){

the two character arrays, array[0] and "-" (string literals internally are represented as character arrays; for example the string literal "-" is stored like an array of two elements { '-', '\0' }) are implicitly converted to pointers to their first elements and the pointers are compared.

In fact you have

if ( &array[0][0] == &"-"[0]){

As the arrays occupy different extents of memory then the expression will always evaluate to logical false.

Even if you will write

if ( "-" == "-" )

then the expression can evaluate either to logical true or false depending on how the compiler stores identical string literals that is either as one string literal or as two string literals (character arrays).

To compare the strings stored in the arrays you need to use the standard string function strcmp declared in the header <string.h> as for example

#include <string.h>

//...

if ( strcmp( array[0], "-" ) == 0 )
{
    //...
}
  • Related