Stack Exchange
Confused about fprintf in busybox
I read ftp source code in busybox, But I can't under what's meaning: "%s %s\r\n"+3
static int ftpcmd(const char *s1, const char *s2)
{
    if (s1) {
        fprintf(control_stream, (s2 ? "%s %s\r\n" : "%s %s\r\n"+3),
                        s1, s2);
        fflush(control_stream);
    }

    do {
        strcpy(buf, "EOF"); /* for ftp_die */
        if (fgets(buf, BUFSZ - 2, control_stream) == NULL) {
            ftp_die(NULL);
        }
    } while (!isdigit(buf[0]) || buf[3] != ' ');

    buf[3] = '\0';
    n = xatou(buf);
    buf[3] = ' ';
    return n;
}


A string literal in an expression decays to a pointer to its first character.
Adding 3 to it results in a pointer to its fourth character.
In this case fprintf() receives the format string "%s\r\n".
The statement:
    fprintf(control_stream, (s2 ? "%s %s\r\n" : "%s %s\r\n"+3), s1, s2);

is quite "hacky" and create confusion, as we see here.
It is better expressed as:
    if (s2) {
        fprintf(control_stream, "%s %s\r\n", s1, s2);
    } else {
        fprintf(control_stream, "%s\r\n", s1);
    }


I am wondering why it was written like that. If the goal was to keep it short, then why not "%s %s\r\n" + (s2 ? 0 : 3)?

@user17732522 We can only guess, and my guess is that the author tried to be "clever", but perhaps not clever enough. Unfortunately, being "clever" is not a good trait for writing good and maintainable code.

@user17732522 They were probably hoping the compiler would fold "%s %s\r\n"+3 into a single address, and store the string "%s %s\r\n" once, as opposed to two separate strings "%s %s\r\n" and "%s\r\n". It's probably very old code, decades

@user253751 Yes, it makes sense to me that they would want to avoid having two different string literals (which are unlikely to be merged into one) for binary size reasons, but trying to avoid the single pointer addition seems of dubious benefit to me. (But as you are saying, it is probably old code and it may have made sense at the time, e.g. for reduced instruction size.)

Lets say we have something like this:
const char format_string[] = "%s %s\r\n";
const char *ptr = &format_string[3];

The pointer ptr will be somewhat equivalent to "%s %s\r\n"+3.
When using ptr as a string it will be "%s\r\n", i.e. it will skip the first %s and the following space.
