Norman
Norman

Reputation: 1

Why is the number output affected by a cout statement?

I am making a console slots game and if I add a cout statement is changes a totally different value. The line has looks like it has nothing to do with it but if you include it won't run the for loop right , I think.

#include <iostream>
#include<stdlib.h>
#include<ctime>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int money = 2000;
int bet = 250;
int winStreak;
void robit(){



} 
int main() {
    int so;
    srand(time(NULL));
    for(int j;j<3;j++){

        int sgh = (rand()%2);
        std::cout<<sgh<<std::endl;
        switch(sgh){
            case 1:
                so =-1;
                break;
            case 2:
                so =+1;
                break;
            default:
                std::cout<<"something is wrong"<<std::endl;
        }

    }
    std::cout<<"\n"<<so;// this is the line if you comment it out the program works fine
    return 0;   
}
``

Upvotes: 0

Views: 42

Answers (2)

김선달
김선달

Reputation: 1562

  1. so is not initialized.

    int so;
    
  2. j is not initialized.

    for(int j;j<3;j++){
    

Upvotes: 1

user93353
user93353

Reputation: 14049

Your program uses the variable j without initializing it.

 for(int j;j<3;j++)

This causes undefined behaviour. The program can do anything.

First fix the problem & then post your problem again.

What is the initial value of j here?

Is it supposed to be int j = 0?

Upvotes: 0

Related Questions