1

I'm writing some code for Arduino and I'm not sure if I'm checking the value of this character variable correctly. Can you please tell me if this is correct:

const char* front = "front";
const char* back = "back";

eyeballs(front);
eyeballs(back);

void eyeballs(const char* frontOrBack){ 

if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);}//end if   
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);}//end else*/
}  
  • 3
    Isn't this more suited to stackoverflow, since there's nothing Arduino-specific about C string comparison? – Timo Jan 21 '16 at 14:00
6

Since you are using C strings (array of characters) instead of the C++ String class, you cannot use the == operator.

Instead, you can use the C style strcmp function, which is also part of the C++ library:

    #include <string.h>
       .
       .
       .

    if (!strcmp(frontOrBack,"front")) {
        digitalWrite(frontEyes, LOW);}//end if   
    else if (!strcmp(frontOrBack,"back")) {
        digitalWrite(backEyes, LOW);}//end else*/
    } 
  • 1
    Don't forget to #include <string.h> – Armandas Jan 21 '16 at 7:24
  • Thank you. Is that the only issue with my code? For some reason the ARduino IDE isn't catching the error. – Michael Rader Jan 21 '16 at 7:24
  • @Armandas thx, updated. – tcrosley Jan 21 '16 at 7:28
  • 1
    @MichaelRader Syntactically, there is nothing wrong with your code, so the compiler doesn't display an error. What you are doing is testing whether the address of the character array frontOrBack passed into the function eyeballs is the same as the address of the constant character arrays "front" or "back", which will always be false. – tcrosley Jan 21 '16 at 7:36
  • 1
    @MichaelRader If you click on the link that I gave for the strcmp function, you will see (under Return Value) that it can return one of three values: >0 (e.g. 1) if the the first character of string1 is greater than the first character of string2; <0 (e.g. -1) if the the first character of string1 is less than the first character of string2; and 0 if the two strings are equal (which is what you are testing for). Putting a ! in front of a variable or function in C or C++ is the same as testing for 0. So I could have written this as "if (strcmp(frontOrBack,"front")==0)" – tcrosley Jan 27 '16 at 10:13
3

Another option would be an enum.

enum
{
   FRONT,
   BACK
}
.
.
.
   if (frontOrBack == FRONT)
   {
      // Stuff
   }
   else if (frontOrBack == BACK)
   {
      // Some other stuff
   }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.