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

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.

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

>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.

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