Hello, I am new to this community, as well as to coding in general. I am having fun learning C, and I’ve generally been able to work through/slam my head into problems until they make sense, but I am confounded by this discrepancy, and I am hoping to have some help with it:

printf("%%c);

Output: %c


#include 

void textGreen(const char* text)
{
    printf("\033[32m%s\033[0m", text);
}

int main()
{
    textGreen("%%c\n");
    return 0;
}

Output: %%c.

Since printf is wrapped into the function, should the text not be outputting with the same behavior? Why is my terminal printing this code without escaping the percent sign? FWIW, the text is green, at the very least.

I am using Ubuntu 23.10, the code was written in KATE, it was compiled in GCC, and it was run on the basic GNOME terminal.

  • CameronDev@programming.dev
    link
    fedilink
    arrow-up
    6
    ·
    10 months ago

    Printf does the %% escaping, but it only does it for the format string (the first argument). %% signals to printf that you want a % instead of a formatting placeholder.

  • smpl@discuss.tchncs.de
    link
    fedilink
    English
    arrow-up
    3
    ·
    10 months ago

    printf simply insert the string from the text argument without parsing it. printf only parse its first argument to see where, and with what formatting, the values of variables should be printed and is not parsing the variables for formatting. Hope it helps and have fun learning C.

  • bizdelnick@lemmy.ml
    link
    fedilink
    arrow-up
    2
    ·
    10 months ago

    In the first example you have %%c in the format string where %% is replaced with %. In the second you have ℅s in the format string that is replased with literal text %%c from the next argument.

    • Classy@sh.itjust.worksOP
      link
      fedilink
      arrow-up
      1
      ·
      10 months ago

      Thank you so much! I didn’t realize that %s changed the runtime rules for escape characters. Is there somewhere that I can find a list of these rules? Because things like \n still work like normal, but then %% does not.

      • bizdelnick@lemmy.ml
        link
        fedilink
        arrow-up
        1
        ·
        10 months ago

        Nothing has changed. %-sequences only work in format string (first argument of printf, it is a feature of printf family of functions). Backslash escaped sequences work everywhere (it is a feature of C language itself).