Monday, May 24, 2010

In C++, two different ways to build 'Hello World'. What's the difference?

im not really sure if the code will come up here.





like.. well..


here's the link , at the bottom you'll see the question i asked with a name called 'Wesley':





http://www.learncpp.com/cpp-tutorial/06-...





i think that link takes you directly to the comment i made.





i'll click 'add details' to this question and attempt to put the code. if it works, woohoo. if not, use the link.

In C++, two different ways to build 'Hello World'. What's the difference?
Your code syntax is wrong...you don't need to declare the main() before implementing it, other functions need to be declared as prototype and then, implement it and then call it in function main.





Remember the main(), is the function where the program starts to execute.





Yes, there are thousands of ways just to print the "hello world".
Reply:Humm, looks a little bit hard to understand your question, I assume you are asking the differences between:


===(a)=====================


#include %26lt;iostream%26gt;


int main()


{


using namespace std;


cout %26lt;%26lt; "Hello world!" %26lt;%26lt; endl;


cin.get();


return 0;


}





=====================





And:





===(b)=====================


#include %26lt;iostream%26gt;





int main();


int main()


{


std::cout %26lt;%26lt; "Hello World!n";


return 0;


}


=====================





First, the 2 statements on case (b) "int main()", are because usually when you use a function inside another, you first have to declare the used function, if its code is below the function that calls it. But in this case it doesn't look to be necessary, since there is only one function (main). You would need to declare it in this case:





void somefunction();


int main()


{


somefunction();


return 0;


}


void somefunction()


{


//do something


}





But you can avoid declaring first somefunction() if you write the code of somefunction above main(), that is:





void somefunction()


{


//do something


}





int main()


{


somefunction();


return 0;


}





Now, about:


using namespace std;


allows you to write: cout %26lt;%26lt; "Hello world!" %26lt;%26lt; endl;


Else you would have to write:


std::cout %26lt;%26lt; "Hello World!n";





(I guess you mean \n instead !n, since \n=endl);





The problem with c++ is that compilers are not absolutely compatible among them, you can use ms vc++ for compiling something and then borland or gnu c won't accept it.


So maybe some things are optional in one compiler, but other would accept only one of them.


No comments:

Post a Comment