Home > Net >  Why is the std::vector not giving any outputs in c
Why is the std::vector not giving any outputs in c

Time:05-21

I don't understand why but the std::vector is not giving anything after i put a class pointer in the array.

// runs at start
void States::AssignState(GameState* state) {
    _nextVacentState  ;
    _states.push_back(state);
}

// executes in a loop
void States::ExecuteCurrentState() {
    // protection incase there is nothing in the array or the current state is not grater than the size of the array (not the problem after i nerrowed the problem down)
    if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return; // there is no states
    if (_currentState >= _states.size() - 1) std::cout << "Error: Current State is grater than all possable states" << std::endl; return;
    
    // The program just freezes at this and i can figure out why
    _states[0]->tick();
    std::printf("S");
}

CodePudding user response:

This is one of the reasons I'd suggest getting in the habit of using curly braces for all if statements, even ones that live on a single line.

A problem line:

if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return;

Let's add some newlines to make it clearer what's happening

if (_nextVacentState == 0) 
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
  return;

That return statement is getting executed unconditionally, because only the first statement after if(_nextVacentState==0) is actually part of the if.

So, what you want:

if (_nextVacentState == 0) 
{
  std::cout << "Error: There is no states, setup some states then try again" << std::endl; 
  return;
}

The same problem is present in the next if check as well.

  • Related