Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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" );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading