F() own function

Hi!

if (chkstr(F("abcd")) {}

bool chkstr(String chkval) {
  byte chklen = chkval.length();
  if (command.substring(0,chklen) == chkval) {
    command.remove(0,chklen);
    return true;
    }
  return false;
  }

How can I do it? Thanks.

Your function chkstr does manipulation to a "object" (I guess a string-variable called "command" which is globally defined.

This is a somehow weird construction.
Usually functions are used to become independant of global defined variables because everything is handed over to the function as parameters.

Using a function for modifying global variables inside a function is even worse than not using functions.

What is the overall thing that you want to do in the end?
Without knowing the context it is impossible to make a suggestion that works good.

best regards Stefan

What do you see if you print chkval in the function ?
Do you think that using the F() macro is appropriate here ?
Where is the command String defined ?
Why use Strings (capital S) and not C style strings(lowercase s) ?
What exactly do you want the function to do ?

It is called by many (about 40) functions and checks more than 100 words.

The below is based on the way the print class works (ArduinoCore-avr/Print.cpp at master · arduino/ArduinoCore-avr · GitHub).

bool chkstr(const __FlashStringHelper *chkval)
{
  PGM_P p = reinterpret_cast<PGM_P>(chkval);
  size_t chklen = strlen_P(p);

  bool isMatch = true;
  for (size_t cnt = 0; cnt < chklen; cnt++)
  {
    unsigned char c = pgm_read_byte(p++);
    if (c != command[cnt])
    {
      isMatch = false;
      break;
    }
  }

  if (isMatch == true)
  {
    command.remove(0, chklen);
  }

  return isMatch;
}

You can speed up finding a solution by posting multiple sentences that explain on an example what your code does.

Of course you are free to post single sentences in every post to slow down the solution to the 100th post

@sterretje
do you really think manipulating a global defined string inside a function is a good idea?

You are God!
Thank you very much.

Where else would (or even could) you manipulate a global variable except inside a function?

nowhere. This is correct. It is always inside a function. mimium function
void setup() or void loop()

This is correct. So my question was unprecise. If a variable is defined global then changing the value should be best possible seeable which IMHO would be void loop()
and not some small function with a name where the name does not tell that this variable will be modifyed.

But of course in his freetime everybody is free to write code in whatever style they like.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.