peacekeeper
peacekeeper

Reputation: 45

Using return 0; in void function is possible or not?

I've recently submit a project of multiply and division of large numbers to my instructor using C programming in code::blocks. in the middle of the code, mistakenly I used return 0; in a void function:

void division_function (char str1[MAX_STR_LEN], char str2[MAX_STR_LEN])
{
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    int num1[len1];
    int num2[len2];

    // In case the second number has more digits:
    if (len2 > len1)
    {
        printf("\nResult of division = 0");
        printf("\nRemainder = %s ", str1);
        return 0 ;
    }
    //rest of the code

anyway after submitting the instructor mailed me that the code failed due to using return a value in void function! I know I should have used (return;) instead of (return 0;) because void function return nothing! my problem is why I don't get any errors in my console! simply I tested this code:

#include <stdio.h>
#include <stdlib.h>
void function ();
int main()
{
    function();
    return 0;
}
void function ()
{
    printf("OK");
    return 0;
}

again I got no error and the output is OK. this time my problem is not getting the error which seems I should get!

Upvotes: 2

Views: 4676

Answers (2)

Bathsheba
Bathsheba

Reputation: 234875

In standard C, it's not possible to return anything with a void function - the compiler is required to issue a diagnostic.

Also if a function is non-void, then you must return something that's either the same type or implicitly convertible to the return type. The exception to this rule is main, where the compiler will insert an implicit return 0; if it's missing.

Note that in C, you should mark your function prototype as having void parameters:

void function (void);

which is an important difference between C and C++.

Unless you can configure the compiler so it fails compilation in such an instance, it is defective and you ought to consider switching it.

Upvotes: 6

Lundin
Lundin

Reputation: 215350

You did get a warning, which you chose to ignore. Codeblocks default installation is a gcc/mingw one, which does give the following warning:

warning: 'return' with a value, in function returning void

If you compile with -pedantic-errors, it will turn into an error.


The recommended setting for beginners is to go Settings -> Compiler, check the following options:

  • Enable all common compiler warnings (-Wall)
  • Enable extra compiler warnings (-Wextra)
  • Treat as errors the warnings demanded by strict ISO C (-pedantic-errors)

Preferably you should also add an option -std=c11 which I don't think exists by default in Codeblocks.

Upvotes: 5

Related Questions