#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
int Die1; /*Random Number 1-6*/
int Die2; /*Random Number 1-6*/
int Total=Die1 + Die2; /*Total value of the two dice*/
/* Generate two random numbers 1-6 for the two dice*/
srand((unsigned)time(NULL));
Die1 = 1 + (rand() % 6); {
printf("Die 1 value is: %d\n", Die1); }
Die2 = 1 + (rand() % 6); {
printf("Die 2 value is: %d\n\n", Die2); }
/* Show the total value of the two dice */
Total= Die1 + Die2; {
printf("Total value is: %d\n\n", Total); }
/* Display win, loss or point message for first throw */
if (Total == 7 || Total == 11) {
printf("Congratulations, you win!\n"); }
elseif (Total == 2 || Total == 3 || Total == 12) {
printf("Sorry, you lose.\n"); }
elseif (Total == 4 || Total == 5 || Total == 6 || Total == 8 || Total == 9 || Total == 10) {
printf("Point to make is: %d\n"); }
printf("Thanks for playing!\n\n");
return 0;
}
This is the error:
Run-Time Check Failure #3 - The variable 'Die1' is being used without being initialized.
Run-Time Check Failure #3 - The variable 'Die2' is being used without being initialized.
What's the reason for this? I created this on Visual Studio 2005 at uni (yes it's a really old version) then I converted it to 2012 and it's given me problems.
Because VS started to actually check code for validity?
Yor code yields you an undefined behavior. In theory it could do anything from exploding your PC to producing a vast amount of antymatter. In practice however it usually just writes some garbage to Total.You can solve it in several ways:
1) Preferred: change that line to int Total; //or better, int Total = 0 . You assigning it value in line 23 anyway.
2) Do
1 2 3
int Die1 = 0;
int Die2 = 0;
int Total=Die1 + Die2;
int Die1;
int Die2;
int Total = Die1 + Die2;
Die1 = rand();
Die2 = rand();
Total = Die1 + Die2;
/* use Total */
You are trying to use Die1 and Die2 on line 3. That is what the compiler thinks as an error, and rightly so, for Total does not need any value at line 3.
Lines 4 and 5 properly set the values for Die1 and Die2, and therefore the assignment to Total on line 6 is valid.