0

so this program requests a positive integer and if provided, it prints it, if not, it continues to request a positive integer.

This is the code:

    #include <stdio.h>

    int 
     get_positive_int(void);

    int main(void)
    {
      int i=get_positive_int();
      printf ("%i\n", i);
    }
    int get_positive_int(void)
    {
      int n;
      do
      {
        printf("positive integer?: \n");
        scanf("%i", &n);
      }
      while (n<1);
    }

My question is, how is the value n returned if there is no return n; at the end? The program runs perfectly with or without return n; Why is that?

FZs
  • 16,581
  • 13
  • 41
  • 50
Gio
  • 11
  • 3
  • 1
    I think this might answer your question: https://stackoverflow.com/questions/4644860/function-returns-value-without-return-statement – Luuk Sep 27 '20 at 09:49
  • It's error in you code, you should have compilation error or warning. It's working just occasionally. – Cy-4AH Sep 27 '20 at 09:49
  • the code is indeed mis-behaving when you enter a non-numeric value like i.e. 'a' – Luuk Sep 27 '20 at 09:57
  • If your compiler doesn't report programming errors like not specifically returning a value when one is declared, increase it's warning verbosity. Or get a better compiler. Almost certainly this is a case where the correct value just happens to be in the register used to store return values. It might fail on a different platform, or with a different compiler. – Kevin Boone Sep 27 '20 at 11:37

0 Answers0