块"If"中的代码不会运行,即使使其为 false 的条件在块内

Code in "If" block doesn't run, even though condition to make it false is inside the block

本文关键字:false 条件 运行 If 代码      更新时间:2023-10-16

我正在运行一个套接字应用程序,该应用程序侦听实时数据并持续处理它。我有一段单独的代码,应该每秒钟执行一次。但这段代码不会执行。让我用代码澄清如下:

在main.cpp中,我有

Client client;
//Code to connect to socket and subscribe to realtime data.
while(client.isConnected){
    client.executeRealTime();
}

在Client.cpp中,我有以下代码:

void Client::executeRealTime(){
    time_t now = time(NULL);
    int currSeconds=now%86400;
    if(currSeconds>13800){
        printf("Before Condition %d %dn",currSeconds,strategyTimer);
        if(currSeconds>strategyTimer){
            printf("After Condition %d %dn",currSeconds,strategyTimer);
            for(int i=0;i<numStrategies;i++){
                if((strategies[i]->isTradeable)==1){
                    strategies[i]->execute(currSeconds);
                }
            }
            strategyTimer=currSeconds;
        }
    }
}

变量strategyTimer的类型为int,代码中的其他任何位置都无法访问它。

该代码在运行时连续打印出"beforeCondition"的printf。我可以从输出中验证,在每一秒,都会出现一个print语句,其中currSeconds比strategyTimer大1,后面跟着print语句"after condition"。然后我注释掉"beforecondition"print语句,然后再次运行代码。这一次,我希望打印语句"After Condition"每秒钟运行一次。但这份声明从未被印刷出来。除非代码进入内部的"if"块,否则无法更改strategyTimer变量。我不明白为什么使用"前条件"打印语句会改变"后条件"打印声明的行为。

请让我了解如何解决这个问题。

我在Windows7中使用eclipse工作区,并使用cygwin工具链进行编译。

Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20198 20198
Before Condition 20199 20198
After Condition 20199 20198
Before Condition 20199 20199
Before Condition 20199 20199
Before Condition 20199 20199

但是当我注释掉Before Condition语句时,我看不到任何输出。

正如我在20多年前调试c程序时发现的那样,printf将东西放入stdout的缓冲区。但stdout没有义务将其实际显示在屏幕上。它会在准备好的时候这样做。

这会产生令人讨厌的效果,让你在错误的地方寻找你的虫子。

正如C中Flushing buffers中所指出的,解决方案是在调试printf语句后使用fflush,或者使用不受此影响的其他日志记录机制。