-1

The following code is giving an error. But when I declare the string static then the same code works.

     char* check(int x1, int x2) 
    {
        char str1[]= "YES";
        char str2[]= "NO";
        if((x2-x1)>0) 
            return str1;
        else 
            return str2;  
    }
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    Youn can try `return x2-x1>0 ? "YES" : "NO";` with the same effect as using `static` – pmg Feb 17 '20 at 13:44

2 Answers2

4

You return pointer to the automatic variables - they do not exist when you leave the scope of the function. So it the Undefined Bahaviour and the code "works" by incident only (as usually UB means - anything may happen)

when you add static keyword you change its storage duration to static and they live as long as the program itself.

Most of the modern compilers will emit the warning. https://godbolt.org/z/_MiuM5

0___________
  • 60,014
  • 4
  • 34
  • 74
3

You are returning the address of local automatically allocated arrays. Those cease to exist when the function exits, which makes the returned address no longer valid.

Making the strings static keeps them alive all the time, fixing the issue.

unwind
  • 391,730
  • 64
  • 469
  • 606