1

Is this code UB or not?

__attribute__((const)) const char* foo() {
 static const char* str = "yo bro";
 return str;   
}

__attribute__((pure)) const char* bar() {
 static const char* str = "ey mate";
 return str;   
}

I'm in particular interested in how pure/const work together with the str declaration.

Andreas
  • 5,086
  • 3
  • 16
  • 36
  • 1
    According to [this](https://stackoverflow.com/a/29117927/2752075), at least the `((pure))` snippet seems to be well-defined. – HolyBlackCat Jan 01 '18 at 13:13
  • 1
    I think both are safe. – Marc Glisse Jan 01 '18 at 13:47
  • 1
    But *why*? Why are you not just doing `return "you bro";` – Antti Haapala -- Слава Україні Jan 01 '18 at 15:36
  • Also what do you mean by "UB"? Undefined by what? – Antti Haapala -- Слава Україні Jan 01 '18 at 15:39
  • The only thing the `__attribute__((pure|const))` says is that the compiler can remember the return value. Nothing else. You can use `__attribute__((const))` on even `rand`, and then have "interesting" results. But the contents of the function itself do not matter. – Antti Haapala -- Слава Україні Jan 01 '18 at 15:53
  • @AnttiHaapala: That's false. If the function body doesn't meet the requirements of the attribute (pure or const) the behavior of a program that calls it is undefined. – R.. GitHub STOP HELPING ICE Jan 01 '18 at 16:58
  • @AnttiHaapala i was worried "yo bro" qualifiy as a global variable, or that since the returned value is an adress to a static variable in function the value can not be determined prior to first invocation. The marked duplicate does not mention the adress to static-variable-in-function-case and that is why i asked. – Andreas Jan 01 '18 at 21:01
  • @AnttiHaapala does return "yo bro" guarantee the adress is the same for all invocations? I prefer using the adress for determining string equality of library defined string constants. – Andreas Jan 01 '18 at 21:03
  • @Andreas so, your question is: is it guaranteed that a string literal stays at the same address in the same translation unit? Then why don't you ask so? – Antti Haapala -- Слава Україні Jan 02 '18 at 03:14
  • @AnttiHaapala Very sorry for being confusing, I'm multitasking questions in the comments (bad manners, sorry). Thanks för the links though, they will answer some of them. The string literal is an interesting aspect but NOT the primary part of the intended question. The primary question is whether or not the initialization of the static variable is a side-effect and/or qualifies as reading a global variable, making the definition incompatible with pure|const function attribute as described by GCC manual. I'll try make a better post and close this one. Many thanks for your input. – Andreas Jan 02 '18 at 08:24

0 Answers0