1

Is this valid and recommended way of reusing const char * in C?

Context: I am writing test case which requires calling the same function twice but using a different C style char string, where string serves as the ID to the begin and end function of the testing API.

    const char *str = "String1";'
    CTX *c = new_context();

    BeginCase(c, "%s", str);

    if (!SUCCESS(c, func1(...)))
        goto out;

    if (!SUCCESS(c, func2(...)))
        goto out;

    EndCase(c, "%s", str);

    str = "String2";

    BeginCase(c, "%s", str);

    if (!SUCCESS(c, func1(...)))
        goto out;

    if (!SUCCESS(c, func2(...)))
        goto out;
out:
    EndCase(c, "%s", str);
    end_ctx(c);
15
  • 4
    Yes, it is valid. If it's recommended or not depends on your use case... Commented May 9, 2022 at 10:27
  • 1
    Initializing with NULL is pointless if the next thing you do is assign "string1" to it. Just initialize it with "string1" from the start. Commented May 9, 2022 at 10:29
  • "Reusing" suggests that you are trying to micro-optimize. I dare say techniques like that are generally NOT recommended (unless needed in highly specific context). Commented May 9, 2022 at 10:30
  • 2
    This can't be answered without any context. You should also narrow down the question to either C or C++, since using C strings in application-layer C++ is often considered bad practice. Commented May 9, 2022 at 10:42
  • 4
    Reusing variables for multiple purposes is a pretty reliable way to introduce bugs. Variables, particularly of primitive types, are very cheap. Commented May 9, 2022 at 10:52

2 Answers 2

2

Is this valid

Yes.

and recommended way

"Recommended" depends on context. I would never recommend using NULL in C++11 or later since nullptr obsoleted it. For large functions, re-using a variable for multiple purposes can make it harder to understand. Initialising a variable and not modifying it is simpler and can be preferable in some cases.

Sign up to request clarification or add additional context in comments.

Comments

1

This syntax specifies that ptr points to a constant character, not that ptr is constant. You can do this, but whether or not you should depends on the situation and needs context that can't be derived from your post, but there is nothing implicitly wrong with this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.