3

The code below compiles in both gcc 10 and clang 11:

int plus_one(int i) { return i+1; }

int main() {
    int i = plus_one(i);
}

What does the standard have to say about this?

Touloudou
  • 2,079
  • 1
  • 17
  • 28
  • 1
    Your code is equivalent to `int i; i = plus_one(i);`. Reading uninitialized variables is UB. – freakish Feb 04 '21 at 17:22
  • It says a lot. `plus_one` names a function definition. It's a global name. It has external linkage. The function has signature `int(int)`. What specifically is of interest to you? – StoryTeller - Unslander Monica Feb 04 '21 at 17:24
  • @freak is that the same for a custom class? It calls the default constructor, and then the assignment operator? – scohe001 Feb 04 '21 at 17:25
  • https://godbolt.org/z/EhxM1j – Marek R Feb 04 '21 at 17:32
  • there are some weird cases that are similar that are actually completely valid. I guess the problem is to reliably decide what is ok and what isnt, so its just either UB or not – 463035818_is_not_an_ai Feb 04 '21 at 17:42
  • @scohe001 no, it's not the same. Objects are all defaulty constructed. Only primitive types aren't. https://stackoverflow.com/questions/3127454/how-do-c-class-members-get-initialized-if-i-dont-do-it-explicitly Note that uninitialized primitive members are still random. – freakish Feb 04 '21 at 17:49
  • 1
    @freakish "uninitialized primitive members are still random" incorrect. Some types like `char` have an indeterminate value. For the most of them (e.g. `int`) reading from an uninitialized variable results in Undefined Behavior which is not the same thing as "having random or garbage values". See [my answer here] to see what that means. – bolov Feb 04 '21 at 18:22
  • @bolov I'm yet to see an uninitialized variable that does anything else than being "random". Either way, it's a nuance. Plus I've already said in the first comment that technically this is UB. – freakish Feb 04 '21 at 18:32
  • 1
    @freakish sorry, forgot to actually link the answer: https://stackoverflow.com/a/60342706/2805305 you have an example here – bolov Feb 04 '21 at 19:00

0 Answers0