Run-Time Check Failure #3 - The variable 'temp2' is being used without being initialized.

Pages: 12
This is a second code I'm trying to run, My first code bricked, so I redid it and I'm still getting errors at temp 2 on line 48.

// 2/26/2021


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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>

#include<string>
using namespace std;


int main()
{//these are values stored to be use later in the program.
    int m, i, kwh;
    string tde;
    float sum1, sum2, temp1, temp2;

    cout << "Enter number of months: " << endl;
    cin >> m;   //reading number of months
    cout << "Enter your tde: " << endl;
    cin.ignore();
    getline(cin, tde); //reading the selected tde 
    i = 1;
    sum1 = 0;
    sum2 = 0;
    for (i = 1;i <= m;i++)    
    {
        cout << "Enter " << i << " month usage(kwh): ";
        cin >> kwh; 
        temp1 = 9.95;
        if (kwh >= 0 && kwh <= 1200)
            temp1 = temp1 + 0.073;             //logic to calculating EFL charges based on kwh
        else if (kwh > 1200 && kwh <= 2000)
            temp1 = temp1 + 0.037;
        else if (kwh > 2000)
            temp1 = temp1 + 0.077;

        if (tde == "ONCOR")
            temp2 = 3.42 + (0.0384470 * kwh);// kwh is value all ready stored
        else if (tde == "CENTER POINT ENERGY")
            temp2 = 5.47 + (0.0403120 * kwh);
        else if (tde == "AEP TEXAS CENTRAL")       
            temp2 = 9.00 + (0.0448460 * kwh);
        else if (tde == "AEP TEXAS NORTH")
            temp2 = 10.53 + (0.0401990 * kwh);
        else if (tde == "TEXAS-NEW MEXICO POWER")
            temp2 = 7.85 + (0.0483210 * kwh);

        sum1 += temp1;
        sum2 += temp2;  // getting the error at this line

        cout << "Charges for " << i << " month based on charges specified in EFL: " << temp1 << endl;
        cout << "Charges for " << i << " month in " << tde << ": " << temp2 << endl;
        cout << " Total charge for " << i << " month is: " << (temp1 + temp2) << endl << endl;              //each month total bill  
    }
    cout << endl;
    cout << "Charges for " << m << " months based on charges specified in EFL: " << sum1 << endl;
    cout << "Charges for " << m << " months in " << tde << ": " << sum2 << endl;
    cout << " Total charge for " << m << " months is: " << (sum1 + sum2) << endl;        


}



The code will run up to this point and then it stops. Second time posting on this subject, apologizes, first time coding something this big.

Severity Code Description Project File Line Suppression State
Warning C6001 Using uninitialized memory 'temp2'. TDU attempt C:\Users\Owner\source\repos\TDU attempt\TDU attempt\TDU attempt.cpp 48

Severity Code Description Project File Line Suppression State
Error (active) E0020 identifier "name" is undefined TDU attempt C:\Users\Owner\source\repos\TDU attempt\TDU attempt\TDU attempt.cpp 7
Last edited on
Edit your post and add in "code tags" to retain indentation, etc., like this:

[code]
your code goes here
[/code]

Do what @dutch says and we can test it.

However, read your error message. Unless tde can be guaranteed to be one of the string values in your if statements then temp2 will never have been given a value.

You could initialise it to 0 when it is defined; however, that simply hides the problem. Better to have a final "else" clause in the sequence of if statements to set temp2. Then you know it has been set somehow.
Last edited on
Ahh, I thought code tag was posting under C++. I see what you all mean.

Ok I'll try this. thanks.
It runs all right for me...no errors. No idea what a "tde" is so if you're going to be selling this code to a client, you'll want to give more of a prompt than just "Enter your tde."

Enter number of months: 
1
Enter your tde: 
ONCOR    
Enter 1 month usage(kwh): 210000
Charges for 1 month based on charges specified in EFL: 10.027
Charges for 1 month in ONCOR: 8077.29
 Total charge for 1 month is: 8087.32


Charges for 1 months based on charges specified in EFL: 10.027
Charges for 1 months in ONCOR: 8077.29
 Total charge for 1 months is: 8087.32


And @lastchance is right, you don't have proper input validation for in case the "tde" is something other than one of your options there.

Best,
max
Hey Max, It runs on web compilers and not my Visual studios. I think other than the sloppy code I have a issue with VS. Ill look more into it when I have more energy. Than all for your help.
I think other than the sloppy code I have a issue with VS.

It's a debug build, running with extra debugging code. It's a good thing, showing you an error that would otherwise not be pointed out.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int m = 0;
    while (true)
    {
        cout << "Enter the number of months:\n";
        cin >> m;
        if (m >= 1 || m <= 1000) break; // I don't know if there's a good upper bound
        cout << "Please enter a number from 1 to 1000.\n";
    }

    // Better to show the user a list and enter a number here.
    int tde = 0;    
    while (true)
    {
        cout << "Enter your tde number:\n"
            "  1. ONCOR\n"
            "  2. CENTER POINT ENERGY\n"
            "  3. AEP TEXAS CENTRAL\n"
            "  4. AEP TEXAS NORTH\n"
            "  5. TEXAS-NEW MEXICO POWER\n";
        cout << ">> ";
        cin >> tde;
        if (tde >= 1 && tde <= 5) break;
        cout << "Please enter 1 to 5\n";
    }

    double sum1 = 0, sum2 = 0;

    for (int i = 1; i <= m; ++i)
    {
        cout << "Enter " << i << " month usage(kwh): ";
        int kwh = 0;
        cin >> kwh;

        double temp1 = 9.95;
        if (kwh <= 1200)
            temp1 += 0.073;
        else if (kwh <= 2000)
            temp1 += 0.037;
        else
            temp1 += 0.077;

        double temp2 = 0;
        switch (tde)
        {
        case 1: 
            temp2 = 3.42 + (0.0384470 * kwh);
            break;
        case 2:
            temp2 = 5.47 + (0.0403120 * kwh);
            break;
        case 3:
            temp2 = 9.00 + (0.0448460 * kwh);
            break;
        case 4:
            temp2 = 10.53 + (0.0401990 * kwh);
            break;
        case 5:
            temp2 = 7.85 + (0.0483210 * kwh);
            break;
        default:
            cout << "Bad tde number: " << tde << '\n';
            exit(EXIT_FAILURE);
        }

        sum1 += temp1;
        sum2 += temp2;

        cout << "Charges for " << i
             << " month based on charges specified in EFL: " << temp1 << '\n';
        cout << "Charges for " << i
             << " month in " << tde << ": " << temp2 << '\n';
        cout << " Total charge for " << i
             << " month is: " << (temp1 + temp2) << "\n\n";
    }

    cout << "\nCharges for " << m
         << " months based on charges specified in EFL: " << sum1 << '\n';
    cout << "Charges for " << m
         << " months in " << tde << ": " << sum2 << '\n';
    cout << "Total charge for " << m
         << " months is: " << (sum1 + sum2) << '\n';
}


I just realized that the above doesn't print the tde in a user-friendly manner. Also, "temp" is almost never a good name. So maybe:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <string>
using namespace std;

int main()
{
    const char* TdeNames[]
    {
        "ONCOR",
        "CENTER POINT ENERGY",
        "AEP TEXAS CENTRAL",
        "AEP TEXAS NORTH",
        "TEXAS-NEW MEXICO POWER"
    };
    int TdeNamesSize = sizeof TdeNames / sizeof TdeNames[0];

    int m = 0;
    while (true)
    {
        cout << "Enter the number of months:\n";
        cin >> m;
        if (m >= 1 || m <= 1000) break;
        cout << "Please enter a number from 1 to 1000.\n";
    }

    int tde = 0;    
    while (true)
    {
        cout << "Enter your tde number:\n";
        for (int i = 0; i < TdeNamesSize; ++i)
            cout << "  " << i + 1 << ". " << TdeNames[i] << '\n';
        cout << ">> ";
        cin >> tde;
        if (tde >= 1 && tde <= TdeNamesSize) break;
        cout << "Please enter 1 to 5\n";
    }
    --tde;

    double eflSum = 0, tdeSum = 0;

    for (int i = 1; i <= m; ++i)
    {
        cout << "Enter " << i << " month usage(kwh): ";
        int kwh = 0;
        cin >> kwh;

        double eflCharge = 9.95;
        if (kwh <= 1200)
            eflCharge += 0.073;
        else if (kwh <= 2000)
            eflCharge += 0.037;
        else
            eflCharge += 0.077;

        double tdeCharge = 0;
        switch (tde)
        {
        case 0: 
            tdeCharge = 3.42 + (0.0384470 * eflCharge);
            break;
        case 1:
            tdeCharge = 5.47 + (0.0403120 * eflCharge);
            break;
        case 2:
            tdeCharge = 9.00 + (0.0448460 * eflCharge);
            break;
        case 3:
            tdeCharge = 10.53 + (0.0401990 * eflCharge);
            break;
        case 4:
            tdeCharge = 7.85 + (0.0483210 * kwh);
            break;
        default:
            cout << "Bad tde number: " << tde << '\n';
            exit(EXIT_FAILURE);
        }

        eflSum += eflCharge;
        tdeSum += tdeCharge;

        cout << "Charges for month " << i
             << " based on charges specified in EFL: " << eflCharge << '\n';
        cout << "Charges for month " << i
             << " in " << TdeNames[tde] << ": " << tdeCharge << '\n';
        cout << "Total charge for month " << i
             << " is: " << (eflCharge + tdeCharge) << "\n\n";
    }

    cout << "\nCharges for " << m
         << " months based on charges specified in EFL: " << eflSum << '\n';
    cout << "Charges for " << m
         << " months in " << TdeNames[tde] << ": " << tdeSum << '\n';
    cout << " Total charge for " << m
         << " months is: " << (eflSum + tdeSum) << '\n';
}


Last edited on
@dutch,
I've been told that it's never a good idea to use while loops like
1
2
3
4
while (true) {}
// and
while (1) {}
// and the like 

because if you make a mistake when writing the code inside them, you can end up with an executable that "goes infinite."

I prefer doing something like this:
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
// Use a boolean
bool loopEnd = true; // initialize it true so the loop will end if there is a mistake inside it.

while (!loopEnd)
{
        cout << "Enter your tde number:\n";

        for (int i = 0; i < TdeNamesSize; ++i)
        {
                cout << "  " << i + 1 << ". " << TdeNames[i] << '\n';
        }
        cout << ">> ";
        cin >> tde;

        if (tde >= 1 && tde <= TdeNamesSize)
        {
                loopEnd = true;
        }
        else
        {
                cout << "Please enter 1 to 5\n";
                loopEnd = false;
        }
}
// This might not be exactly what your code was supposed to do, but you get my point. 

You could also use a do-while, it would accomplish the same thing. But you see that if the programmer makes a mistake and forgets a "true" inside the loop, then it will still end because the boolean was initialized to true. But with a "while (true)" or the like, if the programmer forgets a break inside it, then you get an infinite.

It's just good practice, or so I've heard from friends who do this stuff for a living.

max
Last edited on
@agent_max, You don't know what you're talking about.
I've been told that it's never a good idea to use while loops like while (true)

Whoever told you that is stuffed full of muffins. I sure wouldn't trust any advice like that.

Yes, it can produce an infinite loop if you miscode the while block's escape logic (break;).

That kinda points out you made a boo-boo. Ooops!
I've been told that it's never a good idea to use while loops like


In terms of pure Computer Science, then yes. You wouldn't have break or continue within a loop either. You'd use code like above.

However, in c/c++ use of break/continue is well understood and used. The same as doing validity tests at the start of a function and having separate return statements before the main processing code - rather than having one return at the end and heavily nested if/else statements as computer science might dictate.

The readability and performance issues may make it 'better' to use break et al.

In this respect, IMO whether to use while (true) with break or a test in the condition should be considered on a case by case basis and the appropriate method used. I prefer usually while (true) with break. It usually makes the code easier to read/understand.

For info, in C code this 'infinite' loop used to written as for (;;)
@Furry Guy,
Ok, I admit, the guy who told me that was myself. Because, I've made enough screw-ups when using while(1) loops so that I just don't trust myself with them anymore. But I do still use them sometimes– I have a couple of .txt files with pre-written functions that use while(1) loops. I just copy and paste them into a program, saves a lot of typing.

@dutch,
If I don't know what I'm talking about, perhaps you could point out what I'm doing wrong, that would be more help than just telling me that I'm wrong.

@seeplus,
I have used "break" and "continue" before, but I've made enough mistakes (causing it to go infinite) that I started using them less.
I've made enough screw-ups when using while(1) loops so that I just don't trust myself with them anymore.

If I were to stop using language features more than a few times after I make a muck-up with the features I'd have given up programming, and not just as a hobby, entirely back in the 1990's. Even many of the simplest part of the language gave me problems at times.

Each time I screw something up, I do that A LOT still, I learn from the bone-headed mistake. Not that I won't do it again in the future.

For me part of the fun AND frustration of programming is making a mess of some new bit of coding and figuring out what I did wrong. And how I can either correct the mistakes or figure out I need a different way to attack the problem.

A lot of times I mash around with code snippets to try out different strategies, use different variants of looping. while, do/while or for loops, gauging how using the different types of loop require a different logic strategy within each type loop to get the results I am looking for.

I see making correctable mistakes as part of being a fallible human.
I see what you mean...I guess I shouldn't give up if I make a mistake, just keep trying, eh? Ok, I'll do that. Thanks!
@dutch, If I don't know what I'm talking about, perhaps you could point out what I'm doing wrong, that would be more help than just telling me that I'm wrong.

Fuck you.
Hello TangentJay,

Now that everyone has gone off and ignored the original problem.

First off it is always a good idea to initialize your variables.
1
2
3
int m{}, i{}, kwh{};
string tde;
float sum1{}, sum2{}, temp1{}, temp2{};

This makes it very easy and you do not have to worry about the garbage value of the uninitialized variable. And for a variable like "sum" or "total" you would not want to start with a value of "-107374176.0" for a float or "-9.2559631349317831e+61" for a double and then do a (+=). You are more likely to just get a result that is a bit less small.

Next problem I noticed is: temp1 = 9.95;. Here, unless noted otherwise, the "9.95" is considered a double and you are trying to put the larger double into the smaller float. The compiler will give you a warning. When the code is executed it will basically chop off the part of the double that does not fit into the float. Sometimes the last number of the float will be rounded up before the data from the double is lost.

These days the preferred floating point type is a double. There is still the need for a float in some programs. You may be saving on storage space and ther are still some functions that require a float type variable.

Not initializing your variables when defined it the reason for the run time error when "temp2" never receives a proper value.

When I got the program to run I got this first output:

Enter number of months:
3
Enter your tde:
asdf
Enter 1 month usage(kwh): 2500


As agent max noted I do not know what a "tde" is, actually I do, but do not remember what the letters stand for, so it would be better to spell it out. Unless you are sure that every user knows what "tde" stands for.

As a user not familiar with "tde" and the power companies in the area I would go with dutch's example if using a menu to choose a company before I would let a user enter something like "TEXAS-NEW MEXICO POWER". I have come to the conclusion that on any given day any given user WILL find a way to break your program without even trying no matter how much you try to anticipate any problems. The first thing that comes to mind is that you are expecting capital letters, but some user will enter that name in lower case letters and then nothing will match.

When the program properly I got this output:

Enter number of months: 3
Enter your tde: TEXAS-NEW MEXICO POWER
Enter 1 month usage(kwh): 2000  // >--- To me "Enter usage for month 1 (in kwh): " makes more sense. Its up to you.
Charges for 1 month based on charges specified in EFL: 9.987
Charges for 1 month in TEXAS-NEW MEXICO POWER: 104.492
 Total charge for 1 month is: 114.479

Enter 2 month usage(kwh): 2500
Charges for 2 month based on charges specified in EFL: 10.027
Charges for 2 month in TEXAS-NEW MEXICO POWER: 128.653
 Total charge for 2 month is: 138.679

Enter 3 month usage(kwh): 2250
Charges for 3 month based on charges specified in EFL: 10.027
Charges for 3 month in TEXAS-NEW MEXICO POWER: 116.572
 Total charge for 3 month is: 126.599


Charges for 3 months based on charges specified in EFL: 30.041
Charges for 3 months in TEXAS-NEW MEXICO POWER: 349.717
 Total charge for 3 months is: 379.758



That should give you something to work with.

Andy
@dutch,
If you can't be polite, then please don't bother to respond to my posts. I appreciate corrections, but please, think before you speak, and if you can't say something politely, don't say it at all. Thank you.

@TangentJay, @Handy Andy,
Sorry we got off track. Andy's suggestion is a good one; your menu should probably look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cout << "Power Company TDE options (Enter 1-5): \n"
     << "-------------------------------------\n"
     << "1:  ONCOR \n"
     << "2:  CENTER POINT ENERGY \n"
     << "3:  AEP TEXAS CENTRAL \n"
     << "4:  AEP TEXAS NORTH \n"
     << "5:  TEXAS-NEW MEXICO POWER \n"
     << ": "; // this provides a visual command line
cin >> tde;
//Then have a switch statement to do your calculations
switch (tde)
{ case 1:
     {/* if tde = ONCOR */}
   break;
}
/users/max/tmp/ccfiles/xcrun/untitled.cc:

Power Company TDE options (Enter 1-5): 
-------------------------------------
1:  ONCOR 
2:  CENTER POINT ENERGY 
3:  AEP TEXAS CENTRAL 
4:  AEP TEXAS NORTH 
5:  TEXAS-NEW MEXICO POWER 
:


This way if you want to add another TDE you can just add it to the menu and have another case in the switch statement.

Have a good one,
max
I've made enough screw-ups when using while(1) loops so that I just don't trust myself with them anymore.


We all mess-up and make mistakes from time-to-time. We are human, not machines. As per the saying, "To err is human".

The issue isn't really that mistakes are made, it's how we find, test, deal-with and fix the errors. Testing, fault-finding and debugging are as much a part of life for a programmer as writing code - some might say more so. Finding and fixing problems in code is a skill that needs to be acquired with experience. After a while you start to 'get a feel' for what the problem might be and where to look - together with good usage of the debugger.

If you don't know how to use the debugger, then I'd suggest that you learn this. It is a very important skill that every programmer should have - but is rarely taught/taught well.

At a minimum, you should be able to set break-points, step through code and examine the contents of variables during program execution. How this is done depends upon which debugger/IDE you use.
@TangentJay. Based upon code from your other post here http://www.cplusplus.com/forum/general/276540/

Consider something like:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <vector>
#include <string>
#include <limits>
using namespace std;

struct Charges {
	string tde;
	double month {};
	double kwh {};
};

double getNum(const std::string& prm)
{
	double i {};

	while ((std::cout << prm) && (!(std::cin >> i) || std::cin.peek() != '\n')) {
		std::cout << "Not a number\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return i;
}

int getInt(const std::string& prm)
{
	int i {};

	while ((std::cout << prm) && (!(std::cin >> i) || std::cin.peek() != '\n')) {
		std::cout << "Not an integer\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return i;
}

int main()
{
	const vector<Charges> charges {{"ONCOR", 3.42, 3.8447},
		{"CENTERPOINT ENERGY", 5.47, 4.03110},
		{"AEP TEXAS CENTRAL", 9.0, 4.84460},
		{"AEP TEXAS NORTH", 10.53, 4.01990},
		{"TEXAS - NEW MEXICO POWER", 7.85, 4.83210}};

	const auto months {getInt("Enter number of months: ")};

	cout << '\n';

	size_t tdeno {};

	for (const auto& [name, m, k] : charges)
		cout << ++tdeno << ". " << name << '\n';

	int TDU {};
	double total {};

	while ((TDU = getInt("Enter TDE number (1 - "s + to_string(charges.size()) + "): "s)) < 1 || TDU > charges.size());

	for (int m {1}; m <= months; ++m) {
		const auto usage {getNum("Enter the usage in kWh for month "s + to_string(m) + ". : ")};
		const auto month_charge {charges[TDU - 1].month + charges[TDU - 1].kwh * 0.01 * usage};

		total += month_charge;
		cout << "TDU Delivery charges for month " << m << " : " << month_charge << '\n';
	}

	cout << "\n\nTotal charges for " << months << " months is: " << total << '\n';
}

Last edited on
@seeplus,
I do use the debugger. I use the lldb debugger built-in to the Terminal application. I can't do a whole lot with it yet, but I can run a program, set breakpoints, and check variables. I'm not sure about stepping through, I need to study the manual on it some more.

Example:
Desktop: max$ c++ -std=c++2a -g -o example example.cc
Desktop: max$ lldb example
(lldb) target create "example"
Current executable set to 'example' (x86_64).
[(lldb) b 4
Breakpoint 1: where = example`main + 36 at example.cc:4, address = 0x0000000100001194
[(lldb) run
Process 67233 launched: '/Users/max/Desktop/example' (x86_64)
Hello world!
Process 67233 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100001194 example`main(argc=1, argv=0x00007ffeefbffb38) at example.cc:4
   1   	#include <iostream>
   2   	int main (int argc, char const *argv[])
   3   	{
-> 4   		std::cout << "Hello world!" << std::endl;
   5  	 	return 0;
   6   	}
Target 0: (example) stopped.
[(lldb) c
Process 67233 resuming
Hello world!
Process 67233 exited with status = 0 (0x00000000)
[(lldb) q
Desktop: max$


Pretty different from the Microsoft VS debugger I'll bet! Unless you run it from the command line...
Pages: 12