void

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • matt0046
    New Member
    • Oct 2008
    • 1

    void

    Code:
    #include<stdio.h>
    int main(void){
    printf("hello");
    }
    why is void included in this code?
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    It is unnecessarily included. You can safely remove the void from the parentheses.

    My guess is that it is included to explicitly state that main() takes no arguments: thus, its argument list is void. However, as I said before, you can safely edit this program to

    Code:
    #include<stdio.h>
    int main(){
    printf("hello");
    return 0;
    }
    (Note I added the return 0 line to the end - when you declare main() with int before it, you are promising you will return an integer - so fulfill your promise!)

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      I respect what you say..but my book always writes:
      Code:
      int main(int nNumberOfArgs, char* pszArgs[ ])
      I have searched the book for some comment in explanation but could not find one.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        C++ and C99 (but not C98) allow main to be declared as

        int main(int argc, char *argp[])

        or

        int main(void)

        The void keyword is not required in C++ or C if defining a function but is required in C if you wish to declare a function with no parameters as opposed to declare a function with unspecified parameters where when declaring a function in C++ the void keyword is again optional you can not declare a function with unspecified parameters.

        It is most common for book examples to use the first declaration of main as that is most compatible with most versions of compilers available including ones that perhaps were written before the standards were ratified.

        NOTE: C98 only allows the first version of main given here

        NOTE: That is all standard C and C++, some platforms allow non-standard declarations of main, I know a few micro-controllers whose compilers allow the non-standard

        void main(void)

        but in general it is better to stick to standard declarations.

        Comment

        Working...