Search code examples
cpointersstaticstring-literalsstorage-duration

Function returning pointer into static string


I have this program, that prints Lala. Although i do not understand why i do not get a compilation error in the main function when i call foo(). I suspect it has something to do with the fact that str is static char*, but i do not get it.foo() returns a pointer to a character. So its call shouln't look like this: char* result = foo(); Here is the program:

#include <stdio.h>

char *foo() {
    static char * str = "LalaLalaLalaLala";
    str+=4;
    return str;
}
int main() {
    foo();
    foo();
    printf("%s\n", foo());
    return 0;
}

Can someone explain this to me? Thank you in advance.


Solution

  • Just because a function returns a value doesn't mean you have to use it. It's perfectly valid (though not necessarily wise depending on the context) to not capture or otherwise use the return value of a function. The printf function returns an int value but it's almost never used.

    So the line foo(); is valid code.