const_cast – cpp

Constant casting (const_cast) is when you have a variable that is declared constant but you want to remove that constant restriction from that variable. In normal C language the (int) casting would suffice, but it may throw up some errors that you really did not want!!.. so using const_cast you can remove the constant restriction with abit more safer feeling as such, and also the const_cast would be upgrade/updated on different versions/compilers etc.

To remove the constant casting the syntax for const_cast is

returnvalue = const_cast<return type>(casting value)

where the returnvalue is the value to be returned from the casting, the return type is what you want the returning value type to be and then the value (casting value) is the actual value (constant value) to be cast.

Here is a another example with abit more code

#include <iostream>
 
using namespace std;
 
int main()
{
  const int pies = 3;
  int &newPies = const_cast<int&>(pies);
  cout << "pies = " << pies << endl;
  newPies += 2;
  cout << "new pies = " << newPies << endl;
 
 // where as you cannot alter the old pies value .. 
 // pies+=2;///error !!
  return 0;
}

and the output would be

pies = 3
new pies = 5

Keeping values a constant is a good thing, but sometimes you want to alter the constant value !!.

As someone said on my similar post on code call

Here is some code to demonstrate how to do something similar to the strstr function, from what “dcs” member said “An example that comes to mind would be writing a function similar to C’s strstr function: the strings passed should not be modified by the function and should therefore be const-qualified. But the returned pointer need not be const, even though it may point to a position in the string which was passed as const-qualified.”

#include <iostream>
#include <string.h>
 
using namespace std;
 
char* codecallStrStr(const char* p1, const char* p2)
{
      bool found;
     // loop through the first string
      while (*p1)
      {
	  // if there is a match between the frist string character and the second string character
	  if (*p2 == *p1)
	  {
	    if (strlen(p2) <= strlen(p1))
	    {
	      found = true;
	      for (int i =0; i < strlen(p2); i++)
	      {
		if (p2[i] != p1[i]) {
		  found = false;
		  break;
		}
	      }
	      if (found) 
	      {
		return const_cast<char*>(p1);
	      }
	    }
	  }
	  p1++;
      }
      return 0;
}
 
int main()
{
    char *searchStr = "hi thre there k ";
    char *pr = codecallStrStr(searchStr, "there");
 
    // check to make sure it was found.
    if (pr)
    {
      cout << pr << endl;
    }
    else
      cout << "no found" << endl;
}

output would be

there k

Leave a Reply

Your email address will not be published.