List of harmful (bad practice) things:
using namespace std;
Prefer not to do this. Namespaces were created for a specific reason. And by doing this you destroy everything.
using namespace std;
puts everything from
namespace std
in the global namespace and that can lead to conflicts with names. For example, if you declare a function called
max()
which finds the max of two numbers, there is a chance (stress chance) that it is not going to compile, because you can't have two functions named
max()
, since there already is a function called
max()
in
namespace std
in header
<algorithm>
.
#include <cstdlib>
This is a C library, not a C++ library. Avoid writing C-style C++. Prefer the C++ way. It is safer and richer in content.
#include <ctime>
Same reason as above. This is a C library. All headers beginning with <c...> are from C. For time-like functionality, use the C++
<chrono>
header.
rand() and srand()
are C functions from
<cstdlib>
and as I stated above, don't use that. Use the C++ header
<random>
for random numbers. It might be a bit hard to get used to it in the beginning, but find a good tutorial and all will become clear.
NULL
C++ has this nice thing called
nullptr
. Prefer that over
NULL
because
NULL
is just a macro for 0. That's just a number! It is not used to specify a pointer which is null!!
time()
Like above, this is from
<ctime>
. Use
<chrono>
for time-like functionality.
int coinToss(void)
You declare a function which doesn't take any parameters, so you put
void
as a parameter. Why? This is not necessary in C++.
1 2
|
int x;
x = (rand()%2)+1;
|
You declare and you initialize afterwards. Why? You're constructing an object and then you call the assignment operator on it. That is two functions called.
int x = (rand()%2)+1;
should be preferred. You call the constructor which initializes
x
.
endl
Prefer
'\n'
over
endl
.
endl
calls an extra function
flush
which is not needed most of the time. Sometimes those milliseconds of speed matter.
for(int i=0; i<tossValue; i++)
Prefer
++i
instead of
i++
in C++.
++i
is faster as it modifies the same object, while
i++
creates a new object, modifies the old one, and returns the new object. Convinced yet? It doesn't matter for types like
int
or
long long
because they are simple and fast, but when you're dealing with big classes,
++i
will definitely save you time. So it is definitely good to get into the habit.
Also, I should say that many of the features I've described as replacements come from C++11 and up. So if you have an old compiler, it will not support them. Which is a sign that you should upgrade. Don't live in the 80's and 90's. This is technology, it evolves fast. Use modern stuff.
I'm sorry if I sounded harsh, but you see C-style C++ very and I mean very often and it's hard to get rid of those habits. You just have to try really hard.