Page 84 - C-Language
P. 84

}


        Note that even though a function defined with an empty parameter list takes no arguments, it does
        not provide a prototype for the function, so the compiler will not complain if the function is
        subsequently called with arguments. For example:


         #include <stdio.h>

         static void parameterless()
         {
             printf("%s called\n", __func__);
         }

         int main(void)
         {
             parameterless(3, "arguments", "provided");
             return 0;
         }


        If that code is saved in the file proto79.c, it can be compiled on Unix with GCC (version 7.1.0 on
        macOS Sierra 10.12.5 used for demonstration) like this:


         $ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -pedantic proto79.c -o
         proto79
         $


        If you compile with more stringent options, you get errors:


         $ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes -Wold-
         style-definition -pedantic proto79.c -o proto79
         proto79.c:3:13: error: function declaration isn’t a prototype [-Werror=strict-prototypes]
          static void parameterless()
                      ^~~~~~~~~~~~~
         proto79.c: In function ‘parameterless’:
         proto79.c:3:13: error: old-style function definition [-Werror=old-style-definition]
         cc1: all warnings being treated as errors
         $


        If you give the function the formal prototype static void parameterless(void), then the compilation
        gives errors:


         $ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes -Wold-
         style-definition -pedantic proto79.c -o proto79
         proto79.c: In function ‘main’:
         proto79.c:10:5: error: too many arguments to function ‘parameterless’
              parameterless(3, "arguments", "provided");
              ^~~~~~~~~~~~~
         proto79.c:3:13: note: declared here
          static void parameterless(void)
                      ^~~~~~~~~~~~~
         $


        Moral — always make sure you have prototypes, and make sure your compiler tells you when you
        are not obeying the rules.


        https://riptutorial.com/                                                                               60
   79   80   81   82   83   84   85   86   87   88   89