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.
a source to share
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.
a source to share
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 notconst
toconst
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.
a source to share
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 *.
a source to share
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) { ... }
a source to share