Reputation: 16724
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.
Upvotes: 0
Views: 107
Reputation:
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.
Upvotes: 3
Reputation: 109249
String literals have static storage duration, which means they exist throughout the lifetime of the program. There's no undefined behavior in your code.
Upvotes: 8