newb7777
newb7777

Reputation: 563

Benefits of keyword 'const' in function argument in C language

What benefit does it have to have the keyword const on the function below.

BOOL8 CheckSimilarity(const Name_t NameOne, const Name_t NameTwo)

I always thought that you will have to pass pointers for variables and compare with pointers in the function so it goes to memory location where the variable is stored and compares the variables themselves as in swap function as in K&R?

typedef UINT8 Name_t[5]

Log_t* Log(Name_t Name)
{
   Log_t *point2Log = Log1;
   while (point2Log < Log1)
   {
      if (CheckSimilarity(Name, point2Log->Name))
      {
         return point2Log;
      }
      point2Log++;
   }
   return NULL;
}


BOOL8 CheckSimilarity(const Name_t NameOne, const Name_t NameTwo)
{
    UINT8 count;
    for (count=0; count<5; count++)
    {
        if (NameOne[count] != NameTwo[count])
        {
            return FALSE;
        }
    }
    return TRUE;
}

Upvotes: 0

Views: 228

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

In the case of arguments, it tells the compiler that the function will not modify its arguments. This in turn might enable the compiler to do some shortcuts or optimizations that it otherwise might not have done.

It is also something that your fellow programmers can read, and know that they can call the function without worrying about possible side effects to the contents of e.g. arrays.


And talking about programmers and what they can read, it seems that you have defined Name_t to be an alias for a pointer. Please don't do that, it makes the code harder to read and follow and maintain.

Upvotes: 3

Related Questions