C 基本编程

C 基本编程,c,C,我有一个这样的结构 for(..;..;..) { if(true) { } //statements } 我想在if内写一条语句,除了goto,它将只在if外发送控件,并执行我标记的语句。您可以将if放入一个伪do..while循环如下: for(..;..;..) { do { if () { //use break somewhere here according to your

我有一个这样的结构

for(..;..;..)
{
    if(true)
    {

    }
    //statements

} 

我想在if内写一条语句,除了goto,它将只在if外发送控件,并执行我标记的语句。

您可以将if放入一个伪
do..while
循环如下:

for(..;..;..)
{
    do
    {
        if ()
        {
            //use break somewhere here according to your logic
        }
    }while(false);

    //statements
} 
这将导致
中断
只跳过内部
do..while
循环


do..while
中,条件为
false
,因此在正常if的情况下,循环只运行一次。这个循环只是为了允许一个<代码>中断/代码>在中间。

一个常见的处理这种情况的方法是将<代码>的正文放在一个单独的函数中,然后从函数的中间返回,如果由于某种原因,函数不能完成。函数返回后,将运行
for
循环中的其余语句

void foo(void)
{
    //statements
    //statements

    if ( something_bad_happened )
        return;

    //statements
    //statements

    if ( some_other_bad_thing_happened )
        return;

    //statements
    //statements
}

void bar(void)
{
    for(..;..;..)
    {
        if ( some_foo_is_needed )
            foo();

        //statements
        //statements
    }
}

使用switch语句代替if。你可以在任何时候打破开关。这不是一个非常实用的解决方案。。。但它是有效的

for(..;..;..)
{
    switch(boolean_expression) { //break just leaves this switch statement
    case 0: //false is 0

        break;
    default: //true is not zero
        //statements
        if(something) 
            break;
        //statements you want to skip
        break;
    }
    //statements
}

如果我理解您的问题,即您希望在
If
中编写一条语句,并且仅当该条件为真时才转到标记的语句,那么
转到
语句可能很有用,例如,如果仅当该条件为真时才需要运行
//语句

for(..;..;..)
{
    if(true)
    {
        goto dothis;
    }
    /* other statements */
    return A;

    dothis:;
    //statements

    return B;
}
//语句
不必与
goto
一起位于
for
循环中,例如:

for(..;..;..)
{
    if(true)
    {
        goto dothis;
    }
    /* other statements */
}
return A;

dothis:;
//statements

return B;

你得多解释一下。您是否需要它只用于该迭代,用于嵌套迭代,或者对于所有后续的语句。没有不中断,因为在中断的情况下中断控件将超出for循环,或者一起给出一个更详细的示例。我的意思是,我只想走出if块,执行在我提到的地方编写的语句//我的代码中的语句可以将if放在do while和中使用break。虽然我不能肯定这是否是你想要的。多解释。