c++ - Variable keep getting re- initialized inside loop? -


i'm total beginner , i'm self studying c++, there exercise in jumping c++ in asks write tic tac toe game, half way through program stuck problem inside while loop. not put current code here part of irrelevant question wrote code below similar problem facing in tic tac toe game:

**no matter character give of -char test- variables keep getting re- initialized initial chars because of while loop in main(), way know out of problem change variable's scope global don't want that.

??so how can stop variables getting re-initialized ? can't move while loop main() affect other functions in tic tac toe game... please consider i'm beginner , know loops, conditional statements , bools, not understand big programming words.

thank you

#include <iostream>  int show(int choice, char x_o);  int main(){     int i=0;     int choice;     char x_o=' ';     while(i<2){         //enter 2 , x first time example         //enter 3 , o second time example         std::cin>>choice>>x_o;         show(choice, x_o);         ++i;     } }  int show(int choice, char x_o){     char test='1';     char test2='2';     char test3='3';      switch(choice){         case 1:             test=x_o;             break;         case 2:             test2=x_o;             break;         case 3:             test3=x_o;             break;     }      std::cout<<test2<<'\n'; //test2 prints 'x' first time     //test2 second time prints '2' again } 

it's simple. make them static.

int show(int choice, char x_o){      static char test='1';     static char test2='2';     static char test3='3';     // ... } 

the static keyword means they'll retain value after method exists. want set values elsewhere:

static char test; static char test2; static char test3;  int show(int choice, char x_o){     // ... } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -