0

Is this the below C code an UB? can I access garbage value? if so,can static function make it working fine?

const char *foo_name(int x){ switch(x) { case FOO: return "foo"; case BAA: return "baa"; default: return "unknow"; } } 

I'm a bit confused if printf("%s\n",foo_name(FOO)); is ok according to C std.

4
  • 2
    Why would it be undefined? You are not accessing any garbage value. Commented May 10, 2013 at 20:19
  • the strings exist you are just returning the pointer to it. Its not garbage values... Also you misspelled bar Commented May 10, 2013 at 20:20
  • @Jack: What is your question about specifically? What exactly makes you suspect your function of UB? Commented May 10, 2013 at 20:51
  • 1
    @AndreyT: Because I was thinking that the string behave as "auto". when the functions end up,all allocated memory to function could be cleaned making its return value garbage value. It worked in my C compiler,but I wanted to make sure that it is std and not an extension or somethings like this. I had bad experiences with gcc sometime ago. Now is clean that string literals have static storage duration. I'm going to accept the answer. Commented May 10, 2013 at 21:54

2 Answers 2

8

String literals have static storage duration, which means they exist throughout the lifetime of the program. There's no undefined behavior in your code.

Sign up to request clarification or add additional context in comments.

Comments

3

No UB here. The standard says that string literals have static storage duration.

if so, can static function make it working fine?

For functions, the static modifier means something completely different - it wouldn't solve your (apparently nonexistent) problem.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.