0

A classmate had a function like this :

char* Func( int a )
{
    if( a == 0 )
        return "yes";
    else
        return "no";
}

I know that return a local char* is undefined, but when I asked him he said that since "yes" and "no" wasn't declared as variable it was not undefined behavior.

Who is right? And why?

Aulaulz
  • 459
  • 4
  • 15
  • 1
    It should be `const char *` but beyond that, its acceptable. He's correct; the returned address is still valid and the code otherwise well-formed. – WhozCraig Feb 02 '15 at 06:14
  • You answered what I wanted to know in the delete answer. ( That since "yes" is a string literal, it has a static variable lifetime. Thanks. – Aulaulz Feb 02 '15 at 06:28

2 Answers2

1

There is no local array here, the code shown is well-defined.

The function just returns a pointer of type char and here you are actually just returning a string not a reference to any array.

char *func(int a)
{
   char b[10];
   char *p = b;
   if( a == 0)
   return p;
}

Here you have an error and I think the compiler will report/warn it since you are returning a reference to a local array.The lifetime of array b is just within the func() and when you exit the function the array is not more valid.

Gopi
  • 19,784
  • 4
  • 24
  • 36
-1

Your code is working fine, here is what i tried:

#include <stdio.h>
#include <string.h>

char* Func(int a)
{
    if (a == 0)
        return "yes";
    else
        return "no";
}

int main(int argc, char *argv[])
{
    char a[5] = { 0, };
    strcpy(a, Func(0));
    printf("returned %s",a);
    return 0;
}

this gave output: returned yes


and

#include <stdio.h>
#include <string.h>

char* Func(int a)
{
    if (a == 0)
        return "yes";
    else
        return "no";
}

int main(int argc, char *argv[])
{
    char a[5] = { 0, };
    strcpy(a, Func(1));
    printf("returned %s",a);
    return 0;
}

gave output: returned no

  • 1
    Be cautious that "working fine" is a member of undefined behavior. – tia Feb 02 '15 at 06:20
  • @tia, thanks, here what i have tried to convey is that the behavious is dependant on its usage in the calling function (`main()` in this example) and not the function `Func()` itself, as mentioned in his question. – Ganesh Kamath - 'Code Frenzy' Feb 02 '15 at 06:22