Optimization – Best practice to return an empty string in C

I have two functions, and both can return an empty string, so what is the best practice to save memory and avoid duplicated .txt empty string?

Example

const char* function_one() {
    return "";
}
const char* function_two() {
    return "";
}
int main() {
    printf("One: %s\n", function_one());
    printf("Two: %s\n", function_two());
}

Is this optimization correct ?

const char* empty = "";
const char* function_one() {
    return empty;
}
const char* function_two() {
    return empty;
}
int main() {
    printf("One: %s\n", function_one());
    printf("Two: %s\n", function_two());
}

>Solution :

Usually compilers by default store identical string literals as one string literal in the literal pool. In any case they provide an option that can control that.

So this code

const char* function_one() {
    return "";
}
const char* function_two() {
    return "";
}

in fact is equivalent to this code

const char* empty = "";
const char* function_one() {
    return empty;
}
const char* function_two() {
    return empty;
}

except in the last code there is created a redundant global variable.

You can check the default strategy of your compiler for example the following wat

#include <stdio.h>

const char* function_one() {
    return "";
}
const char* function_two() {
    return "";
}

int main(void) {
    printf( "%s\n", function_one() == function_two() ? "equal" : "not equal" );
}

Leave a Reply