I've rarely used char* in my past. I just try to avoid them and use strings as much as possible. Therefore I kinda lack knowledge about char* strings at my work.
I would like to know if this is safe code for returning a char*
Normally this is bad code because you return a pointer to a temporary.
But as far as i know it is safe to return temp string literals, and in this case we don't have a typical pointer to a temp.
but does group + strlen(formatAddition) create a string literal?
strlen(formatAddition) is a number. The length of the char* style string.
In this case, the number 5.
So the code is effectively: return group + 5;
So you're returning a char*, pointing to the fifth letter of the whatever group is pointing at. Is that what you're trying to do? Effectively, get back a pointer into the string you passed in?
If group is pointing to a c-style string less than five letters long, this is massively unsafe.
If you can guarantee that group will be pointing at something long enough, such as "Test_12345", then you'll get back a pointer to the c-style string "12345".
I don't know if I'd call if "safe" but there's no reason why it wouldn't work.
> I would like to know if this is safe code for returning a char*
It is not compileable code.
1 2 3
char* formatAddition = "Test_";
// g++: error: ISO C++ forbids converting a string constant to 'char*'
// clang++: ISO C++11 does not allow conversion from string literal to 'char *'
interesting, because it compiled on all c++11 compilers :o
char* formatAddition = "Test_";
I've tried it on compiler explorer to make sure we aren't using a compiler I'm not aware of.
It works there as well
and i were wrong, group isn't a string literal, it is a char* which gets assinged somewhere
and and the variables which get the return types are non const therefore i can't return a const char*
Compile with both -std-c++11 (or better c++14) and pedantic-errors (both are required)
If either is missing, C++ conformance (to the extent that the implementation is capable of conforming) is not enforced; the code is assumed to be in a non-standard dialect of C++ which is wildly popular amongst the Linux crowd.
is my updated version now, input isn't const because i get a non const passed in
and return is also non const because the variables which get the return typed assigned to are also non const.
and as mentioned group is no string literal, that was wrong information
> group isn't a string literal, it is a char* which gets assinged somewhere
> and and the variables which get the return types are non const therefore i can't return a const char*