Pearman
Pearman

Reputation: 1068

Variable changes value when passed to function?

I feel like an idiot. When I pass a variable to the function it results in a strange output like 6.2+e003 instead of the value that the variable holds. What am I doing wrong?

The x in main and the x in the function are different?

main:

int x, y;

while(system.WindowOpen())
{
    x++;
    y++;
    bg.Draw2D();
    bob.Think(x, y);
    riley.Think(x, y);
    system.Render(0);
}

class method:

void Organism::Think(double x, double y)
{
    std::cout << "X: " << x << "\n";
    std::vector<double> food;
    food.push_back(x);
    food.push_back(y);
    std::cout << "VECTOR: " << food[0] << " " << food[1] << "\n";
    std::vector<double> path;
    if(refresh.IsTime()) {
        std::cout << "\nFOOD VECTOR: \n" << food[0]
                  << "\n" << food[1] << "\n";

        path = brian.GetOutput(food);


        organism.Translate2D(path[0], path[1]);

        if(organism.IsOffScreen2D(resX, resY) == 'l' )
            organism.SetPos2D(resX, organism.GetY());
        if(organism.IsOffScreen2D(resX, resY) == 'r')
            organism.SetPos2D(0, organism.GetY());
        if(organism.IsOffScreen2D(resX, resY) == 't')
            organism.SetPos2D(organism.GetX(), resY);
        if(organism.IsOffScreen2D(resX, resY) == 'b')
            organism.SetPos2D(organism.GetX(), 0);
    };

    font.DrawNumber2D(x, 50, 50);
    font.DrawNumber2D(y, 50, 100);
    organism.Draw2D();
}

Upvotes: 0

Views: 183

Answers (2)

Pearman
Pearman

Reputation: 1068

I was writing outside the bounds of a vector. I switched from using the [] operators to using the .at() and found my bug right away. Just a bit of memory corruption. I feel quite silly. Thanks all!

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227370

Both x and y are uninitialized here:

int x, y;

so they can hold any value, and reading from them is undefined behaviour. You should initialize them:

int x = 0
int y = 0;

Upvotes: 4

Related Questions