首页 > 解决方案 > Why do semi-colons in c++ seem to implicitly handle errors? [tldr: they don't]

问题描述

This is in the visual studio 2019 community edition distribution of c++ on windows. I have this code below:

char c;
c = getc(stdin); // reading in some value
while(c != ';');
{
    // do something
}

When the semi-colon was on the end of the while loop it stopped an exception from being thrown. One that seemed to be triggered in the loop, where 'do something' is. When I change it to this:

char c;
c = getc(stdin); // reading in some value
while(c != ';')
{
    // do something -> exception thrown
}

Can anyone explain this to me? EDIT: Just to be more specific. In the '// do something' part of the loop I was changing the value of c and so forth, I didn't think it was relevant so I didn't include it.

标签: c++visual-studioexceptionvisual-c++while-loop

解决方案


编码

while(c != ';');
{
    // Do something
}

相当于

while(c != ';')
{
    // Empty body
}
{
    // Do something
}

所以你首先有一个(可能)无限循环,然后是它自己的嵌套范围内的“做某事”代码。


推荐阅读