简体   繁体   中英

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM