Cheers everyone, Newbie on C++ board!
I'm a beginner with C++, currently working through a C++ beginners book teaching game programming which also contains small review exercises. This is the first exercise i did - and - yay! it works! But is it also good code?
- Is it good or bad to declare variables in the way i did? Or should i rather write a line for every single int variable instead?
- Should i rather write a separate line for calculations before they are being used or is it O.k. the way i did in my code?
Everything works and there are no compiler errors. I just cannot help but feel that doing it this way could potentially lead to problems in bigger projects. In case of this exercise the variables should remain uninitialized until user input and subsequent calculation of final score and average score takes place.
I just can't help but feel that just because it works in this specific case it could lead to trouble in upcoming bigger projects. Of course i would write extra lines when i know that some variable or whatever does need to hold a constant value. But there might also be cases coming up where i would declare variables and then use them all over the place, only to find that they might need a constant value - what then? What would happen in such cases?
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
// gameScores.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int finalScore, avgScore, pl1, pl2, pl3;
cout << "Please enter the score player 1 achieved:" << endl;
cin >> pl1;
cout << "Now enter the score player 2 achieved: " << endl;
cin >> pl2;
cout << "Finally enter the score player 3 achieved: " << endl;
cin >> pl3;
cout << "The final score off all three player is: " << (finalScore = pl1 + pl2 + pl3) << endl;
cout << "The average score off all three players equals: " << (avgScore = finalScore / 3) << "." << endl;
return 0;
}
|
Thanks for taking your time to read and hopefully shed some light on this newbies coding adventure darkness!
Regards
Misenna