int main(void) { func(); func(6); return 0; } int func(

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abhi17
    New Member
    • Feb 2010
    • 6

    int main(void) { func(); func(6); return 0; } int func(

    int main(void)
    {
    func();
    func(6);
    return 0;
    }
    int func(int x)
    {
    printf("hello world");
    }

    why this code gave no error and printed hello world twice ????
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This situation occurs due to not using function prototypes. If you do, you will get an error and the build will fail.

    As it is, func() produces a warning that it is not defined and is assumed an extern returning an int. The linker sees func() as an unresolved function and it has func(int) available. In C, func() just means a "function named func with unspcified arguments". So it links a call to func(int). Later it links func(6) to
    func(int) and off you go.

    This situation was fixed in C++ by implementing function overloading. since func() in C++ is a function with no arguments and func(int) is a different function with one argument.

    I suggest in C that a) never accept a build as OK if it has any warnings and b) always use function prototypes.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      If you are getting no compiler warnings or errors for that code you could probably afford to set the warning level of your compiler higher.

      Comment

      Working...