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*/
}
asked Jan 21, 2016 at 7:10
-
3Isn't this more suited to stackoverflow, since there's nothing Arduino-specific about C string comparison?Timo– Timo2016年01月21日 14:00:41 +00:00Commented Jan 21, 2016 at 14:00
2 Answers 2
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*/
}
answered Jan 21, 2016 at 7:22
-
1Don't forget to #include <string.h>Armandas– Armandas2016年01月21日 07:24:13 +00:00Commented Jan 21, 2016 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– Michael Rader2016年01月21日 07:24:23 +00:00Commented Jan 21, 2016 at 7:24
-
@Armandas thx, updated.tcrosley– tcrosley2016年01月21日 07:28:06 +00:00Commented Jan 21, 2016 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– tcrosley2016年01月21日 07:36:55 +00:00Commented Jan 21, 2016 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– tcrosley2016年01月27日 10:13:06 +00:00Commented Jan 27, 2016 at 10:13
Another option would be an enum.
enum
{
FRONT,
BACK
}
.
.
.
if (frontOrBack == FRONT)
{
// Stuff
}
else if (frontOrBack == BACK)
{
// Some other stuff
}
answered Jan 21, 2016 at 13:49
Swarles BarkelySwarles Barkely
lang-c