-3

I have the next strange situation:

void refill (Car* car) {
    if ( car->model == "BM234" ) {
        car->fuel = 65;
    } else {
        car->fuel = 51;
    }
}

My struct Car has af field called model and it is "BM234". But the result of the comparison is car->fuel = 51((( Why two equal strings for C are not equal?

user3402740
  • 45
  • 1
  • 7
  • What is the type of car->model? – mrVoid Sep 12 '14 at 12:54
  • 3
    There is a search option in StackOverflow, please use it as a such common question has been asked many times. – Jack Sep 12 '14 at 12:56
  • The type of car->model is char model[100]. I used the search option ans saw about strcmp. But my question here is why my logic is wrong. I want to undestand it. – user3402740 Sep 12 '14 at 13:00
  • Your logic is only "wrong" in the sense that C **does not allow** this notation to compare strings. It's the same for other 'logical' operations. In Python, for example, you can 'add' and 'multiply' strings: `x = 5*"hello"`, which do exactly what one *logically* would expect. Alas, there is a vast difference between 'logically' and 'what the language allows'. – Jongware Sep 12 '14 at 14:03

3 Answers3

0

if ( car->model == "BM234" ) {

this is not way to compare string in C. == is used for compare single character.

use strcmp to compare string in C.

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
0

The == operator in C compares pointers. So if you have two different pointers, both pointing to the strings with the exact same characters, the result will be 0 or false.

To compare strings use strcmp. strcmp returns 0 if both strings are equal, a negative number if the first string should be sorted before the second one, and a positive number if the first string should be sorted after the second one. So you would write

if (strcmp (car->model, "BM234") == 0) ...
gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

You can use

strcmp( car->model,"BM234")==0

If you want to use == you must using operator overloading for your class or struct

Mehdi Haghshenas
  • 2,433
  • 1
  • 16
  • 35