2

I stumbled upon this behaviour while helping a friend with his homework.

#include "stdio.h"
int f(int n) {
    if (n == 0) return 1;
    n * f(n-1);
}

int main(void) {
    printf("%d\n", f(5));
    return 0;
}

Given this piece of code, gcc-5.4.0-r3 (Gentoo) returns 1 when compiled with any optimization level. What I find most astonishing is though that gcc compiles without warnings. Only using -Wall it issues a "control flow may reach end of non-void function" warning.

clang is a bit more interesting. It generates 0 when compiled without optimizations, but 1 when compiled with optimizations. Contrary to gcc, clang warns the user about the possible control flow error.

According to the C89 standard, this is undefined behaviour. I suspect that gcc (and clang with optimizations) propagate the innermost factorial return to the top, because when the constant changes, so does the return value.

Can someone explain what exactly is happening?

ThreeFx
  • 7,250
  • 1
  • 27
  • 51
  • 2
    On Intel, generally the function return is placed in the `ax` register. So without an explicit return statement, you get what was last placed in `ax`. – Paul Ogilvie Oct 02 '17 at 18:12
  • 1
    https://stackoverflow.com/questions/4644860/function-returns-value-without-return-statement/4644913 – AnT stands with Russia Oct 02 '17 at 18:12
  • 2
    Just curious about why you want to interpret undefined behaviour. You cannot rely on the behaviour, so why the analysis? – Stephan Lechner Oct 02 '17 at 18:15
  • 1
    Compile to asm and check the code. Ultimately that will tell you what is happing *in this instance* (and not-at-all anything useful beyond that). – WhozCraig Oct 02 '17 at 18:16
  • @StephanLechner I'm interested in the compiler internals that lead to this specific behavior. – ThreeFx Oct 02 '17 at 18:19
  • huh, `gcc` warns too: `a.c:4:7: warning: value computed is not used [-Wunused-value] a.c:5:1: warning: control reaches end of non-void function [-Wreturn-type]` Did you ask for warnings (`-Wall -Wextra -pedantic`)? – ikegami Oct 02 '17 at 18:29
  • @ikegami I misclarified: gcc without and warning flags reports no warnings. – ThreeFx Oct 02 '17 at 18:31
  • Yeah, and my phone makes no sound when I leave mute on. Why is that surprising??? – ikegami Oct 02 '17 at 18:32

0 Answers0