1

Learning C. Working with user-defind functions.

#include <stdio.h>
#include <stdlib.h>

int print_random_matrix (int m, int n);

void main (void)
{
    int m, n;

    printf("m: "); scanf("%d", &m);
    printf("n: ");   scanf("%d", &n);

    print_random_matrix(m, n);
}

int print_random_matrix (int m, int n)
{
    int i, j, a[20][20];
    for (i= 1; i<= m; i++)
    {
        for (j= 1; j<= n; j++)
        {
             printf("%d ", rand()%10);
        }
        printf("\n");
    }
    //why does this work without RETURN?
}

As far as I know you need a return statement to return the value from the function you defined, but it works without one and I don't understand why. This code does not look right to me.

Is the code correct?

&

Why does it work right now?

&

How do I write the print_random_matrix function with a return statement?(if I have to)

Dodoke
  • 19
  • 1

1 Answers1

3

Failing to return a value from a function with a non- void return type invokes undefined behavior.

One of the ways undefined behavior can manifest itself is that the program appears to work properly. A seemingly unrelated change can however change how undefined behavior will manifest. In this case you never attempt to use the return value so that's probably why you don't see any strange behavior.

So just because a program could crash or output strange things doesn't mean it will.

The proper thing to do in this particular case is to change the function's return type to void.

EDIT:

Even though you fail to return a value from the function, your program works normally because you don't attempt to use that return value. If you did try to use the return value, then you invoke undefined behavior. Still, you should either change the function to return void or return some meaningful value.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    Technically I think failing to return a value is not undefined behaviour unless the caller accesses the return value, which is not the case here. – Arkku Dec 26 '18 at 16:39
  • @Arkku *failing to return a value is not undefined behaviour unless the caller accesses the return value* I seem to remember something similar. I can't seem to find a cite in the C standard, however. – Andrew Henle Dec 26 '18 at 16:43
  • 1
    @Arkku - You are indeed correct. It's [6.9.1p12](https://port70.net/~nsz/c/c11/n1570.html#6.9.1p12). – StoryTeller - Unslander Monica Dec 26 '18 at 16:46