C++ Weird Loop Behavior due to no return

  Kiến thức lập trình

I encountered this weird issue where I had forgotten to change return type of a function from uint64 to void, and wasn’t returning anything from the function and this resulted in my program being stuck in a loop. My code looked something like the following:

uint64_t foo(uint64_t args){
    std::cout<<"start foo"<< std::endl;
    uint64_t x = args->now - args->X;
    float y = bar(x);
    args->z = args->C * y;
    if (args->z > 10){
        args->X = args->now;
        args->S -= args->z;
    }
    std::cout<<"end foo"<< std::endl;
}


int main(int argc, char *argv[]) {
    std::cout<<"before foo"<< std::endl;
    foo(args);
    std::cout<<"after foo"<< std::endl;
}

The output I was getting was:

before foo
end foo
end foo
end foo
end foo

If I change order of “start foo” print, It would also become part of the loop at some places. This disappeared once I changed the function return type. Would anyone know why this was happening?

LEAVE A COMMENT