I have a routine that compares two variables X and Y and allocates a value to a uint8_t but when I try to use the text in the uint8_t I get a message that it was not declared. Please see my code.
if (!x && !y) uint8_t data[] = "First argument";
else if (!x && y) uint8_t data[] = "Second argument";
else if (x && !y) uint8_t data[] = " Third argument";
else if (x && y) uint8_t data[] = Fourth argument";
The correct approach is to make the data array global, allocate memory for it in advance, and then fill it with the desired text, for example using the strcpy() method:
const char *source = "First argument"; // Static message
char data[20]; // Destination array
if (!x && !y)
{
// Copy the static text to the data array
strcpy(data, source, sizeof(source) );
}
There might not be a need for "extra" memory.
How about:
char *data="";
if (!x && !y) data = "First argument";
else if (!x && y) data = "Second argument";
else if (x && !y) data = " Third argument";
else if (x && y) data = "Fourth argument";
Serial.println(data);
there are unused variable warnings for each line, with Warnings set at More and All (but not Default); and no "conflicting declaration" error for the differing types because they are in separate blocks. (Brace initialization will trigger a narrowing conversion error if there is overflow; plain old equal-assignment might generate a warning.)
The compiler would be happier if that was declared const char * -- those strings might not be writable, and any duplicates likely pooled. This works fine to point at one of them and read from there. If the intent is to modify that buffer, you'll want to make a copy.