Archived

This topic is now archived and is closed to further replies.

the main function

This topic is 5022 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''m sure this is a really dumb question but I''m curious. Why is the following code not allowed:
int main(int argc, char *argv[])
{
  int add(int, int);//function prototype

  
  //function definition

  int add(int num, int num2) 
  { 
    return num + num2; 
  }
  
  //call the function    

  cout << add(2,2) << endl;
     
  system("PAUSE");	
  return 0;
}
[\source]
 
How about them apples?

Share this post


Link to post
Share on other sites
Move the function prototype and function declaration outside of main(). You cannot have function prototypes/definitions inside other functions.


int add(int, int);//function prototype



//function definition

int add(int num, int num2)
{
return num + num2;
}

int main(int argc, char *argv[])
{
//call the function

cout << add(2,2) << endl;

system("PAUSE");
return 0;
}


-------
Andrew
PlaneShift - A MMORPG in development.



[edited by - acraig on March 17, 2004 8:18:33 PM]

[edited by - acraig on March 17, 2004 8:19:41 PM]

Share this post


Link to post
Share on other sites
it's not allowed because you can't declare functions inside of other functions. that's just the way the language works.

-me

[edited by - Palidine on March 17, 2004 8:39:51 PM]

Share this post


Link to post
Share on other sites
Thanks for the replies guys. Declaring the function within main seems to be allowed although I would not think that this is good practice. Its just the function definition that is not allowed. But as you say if that''s just the way the language is then so be it.

How about them apples?

Share this post


Link to post
Share on other sites
so its not possible to make functions local only to another function? as in, theres no such thing is local functions, only global ones? sigh... i hate my school. my first semester programming teacher told us to make functions inside another function. his logic was, "its just like variables, you wouldnt make a global variable if only one function uses it"

Share this post


Link to post
Share on other sites
ya no i think i''m wrong. it does seem to work. i just happen to dislike local functions. i''ve never seen them used in anything i''ve worked on, but mostly i work on OO designs. they are perhaps more relevant in procedural design.

sorry for any confusion i have sewn

-me

Share this post


Link to post
Share on other sites
acraig I've tried the same thing in Dev C++ and it does work but in C only and not C++. The compiler does give a warning though. Does anyone know why it works in C and not C++? Is it just the way the language is?

How about them apples?

[edited by - popcorn on March 17, 2004 8:54:39 PM]

Share this post


Link to post
Share on other sites