块"If"中的代码不会运行,即使使其为 false 的条件在块内
Code in "If" block doesn't run, even though condition to make it false is inside the block
我正在运行一个套接字应用程序,该应用程序侦听实时数据并持续处理它。我有一段单独的代码,应该每秒钟执行一次。但这段代码不会执行。让我用代码澄清如下:
在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
,或者使用不受此影响的其他日志记录机制。
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 伪造事实↔false
- QueryWorkingSet总是返回false
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 当我的 if 条件计算结果为 false 时,我的 else 块将不会执行
- 为什么当 while 循环中的 if 条件变为 false 时,我的函数不输出最后一条语句?
- if 语句在条件为真时返回 false
- C if(false)条件评估
- 如果语句计算结果为 false,即使条件为真
- 具有自定义返回类型和"false"返回条件的函数?
- 如果任何条件是错误的,如何从for循环中返回false
- 为什么如果条件为false,为什么仍会对语句进行辩护
- 块"If"中的代码不会运行,即使使其为 false 的条件在块内
- 在条件为false之前循环时退出
- 为什么这个条件返回 false,但在主函数中它返回 true
- 如果某个条件语句中的某些内容导致该条件语句不再为true/false,则该语句是否停止执行
- 为什么逻辑运算符 false 在条件下不起作用