+ 1
Reason for the standard coding template in c++
Is there any reason we need to have #include <iostream> using namespace std; int main(){ return 0 } in every code? I have only about a week of coding experience and it has all come from SoloLearn. It seems really repetitive because every c++ code uses this template to the point that every mobile c++ compiler I have seen automatically include it. It seems so unnecessary to me to the point that I don’t really understand why it is a thing. I suspect it has something to do with c. Thanks!
8 ответов
+ 3
You may use any c header in C++, but with a c before the name and after omitting the .h.
Eg - math.h -> cmath.
And for details on any of the C++ headers:
www.cplusplus.com/reference/
+ 2
To add to what Ace said, this is just the way c++ works. The main() function is where the executable looks when it runs the program and probably always will for c++. There's really no way around it. If you look at other languages, like Java, for example, you need a program class and then the public static void main() function to run every program; if I am not correct in saying this, someone please correct me.
Also, the iostream header includes much more than just input and output, so that's why it's a default include for many compilers, as you've mentioned.
+ 2
Yes! Some of my favorites include (pun intended):
<cmath>
<vector>
<ctime>
<cstdlib>
<map>
<memory>
+ 2
@Kinshuk Vasisht, when you say omit the .h is that referencing that the header in c has the .h while in c++ it instead has the c at the beginning? Also, since we can use any header from c in c++, what is it exactly that makes the two different from one another? And why would I chose one language over the other?
Thanks everyone again! These answers are very helpful!
+ 2
Yes, for C you would include the math header like so:
#include <math.h>
while in c++, you write it:
#include <cmath>
This is the same for all of the c header files.
As for your second question, that is a very controversial question. I've heard many many opinions on the matter. The fact is that you can do things in each language that are exclusive to that language, but C++ can also do more, in general. You'll hear many people say it's just c with more stuff, and that's not entirely true. In my opinion, I think they both have their uses, but C++ is just easier for me.
+ 1
without using namespace std; you would have to type std::cout, std::cin, etc. iostream is a header, and int main(){} is the main function. Every program in c++ MUST have a main function (which is also, first executed). I dont have a lot of experience, but I think that everything I said was correct (If i wasnt, somebody please correct me). Hope its clear now.
+ 1
So are there different headers you can use for c++? I have seen different headers for c, but only #include <iostream> for c++. If so, what would be some implications of using a different header? (Thanks for your responses so far, they have been very helpful)