Home > Software design >  Reuse pointer to const strings in C
Reuse pointer to const strings in C

Time:05-10

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);

CodePudding user response:

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.

CodePudding user response:

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.

  • Related