Declaration Confuse
-
Finally, I solved my previous problem Re: Sum Multiple Value At a Time - C / C++ / MFC Discussion Boards[^] I have a question in declaration why we declare sum = 0; if we declare only sum; what happen, what is the meaning of 0 and please clarify the function sum = sum+workhours; I have to understand whole thing.
#include
using namespace std;
int main ()
{int sum = 0; int workhours; int numemployee; int employeewage; int wage = 0; cout << "Enter Number of Employee:"; cin >> numemployee; for(int i=0;i\> workhours; sum=sum+workhours; cout << "Enter Work/hrs Wage " << (i+1) <<":"; cin >> employeewage; wage=wage+employeewage; } cout << "Total Work Hours: " << sum <
-
Finally, I solved my previous problem Re: Sum Multiple Value At a Time - C / C++ / MFC Discussion Boards[^] I have a question in declaration why we declare sum = 0; if we declare only sum; what happen, what is the meaning of 0 and please clarify the function sum = sum+workhours; I have to understand whole thing.
#include
using namespace std;
int main ()
{int sum = 0; int workhours; int numemployee; int employeewage; int wage = 0; cout << "Enter Number of Employee:"; cin >> numemployee; for(int i=0;i\> workhours; sum=sum+workhours; cout << "Enter Work/hrs Wage " << (i+1) <<":"; cin >> employeewage; wage=wage+employeewage; } cout << "Total Work Hours: " << sum <
Well two problems if we imagine it uninitialized that is it will have some random value. The start value could be any integer value. 1.) Your sum starts at some random value then you do this line sum=sum+workhours; So your answer is some random value + the work hours. Why bother calculating anything the total is just some random number. 2.) You print the answer even if you had zero employees you would print some random value. The compiler will actually throw a warning about this line using uninitialized value due to that The take home message here is variables don't magically start at zero if you want them to start as zero you need to set it to zero. There is one subtlety here that when you are in debug mode it will initialize all variables to zero. That doesn't happen in release mode. So new users when debugging often get caught out because when they look in debug mode sum will start as zero. So the key here is don't set it to zero, compile in release mode ignoring the warning and run your code and watch some random number display. You will have your answer.
In vino veritas