When to use const char *

If I have an api function that expects a 14 digit input and returns a 6 digit output. I basically define input as const char *. will this be the right and safe thing? also why i dont want to just do char *, which i could, but in this case it seems more reasonable to use const char *, especially since it is the api i provide. so for different input values ​​i generate 6 digit codes.

+2


a source to share


7 replies


When you speak const char *c

, you are telling the compiler that you will not make any changes to the data it points to c

. Thus, it is good practice if you are not going to directly modify your input.



+4


a source


I'm not sure why you are using char pointers, where you can use std::string

:

std::string code(const std::string& input)
{ ... }

      



If you have no choice, use const char*

gives assurance to the user that you will not change their data, especially if it was a string literal in which the change is undefined.

+10


a source


By using const, you promise your user that you will not change the passed string. It becomes part of the API to help define the behavior of your function. It also allows users to pass in constant strings, including literal strings such as "mystring".

+4


a source


You get several benefits to use const

:

  • It documents your code, the user doesn't know that this line will be harmed.
  • You allow the user to send const char*

    which he may have. The conversion from not const

    to const

    is automatic. Another way is something to avoid (and is done explicitly, and can sometimes lead to undefined behavior)
  • You let the compiler test you. The compiler can now check that you are not accidentally modifying the custom string.
+1


a source


String literals have a static storage class (they exist throughout the entire program) and may or may not be split if the same string literal refers to multiple locations in the program. The effect of changing a string literal is undefined; thus, you must always specify a pointer to a string literal as const char *.

+1


a source


You need to use const char *

anywhere you pass the string literal, or the compiler will stop (unless you want to convert it to std::string

).

0


a source


const char*

commonly used in parameters, stating that your function will not modify that string.

void function(char* modified_str, const char* not_modified_str) { ... }

      

If you are returning const char*

, what you want to say is not obvious. You are trying to say that no one should change the returned string, but you still (I think they will) transfer ownership of the caller, so it will have to be called delete[]

on char for your function to return.

Generally speaking, use std::string

then your function will look like this:

std::string function(std::string& modified_str, const std::string& not_modified_str) { ... }

      

0


a source







All Articles