简体   繁体   English

C 程序错误代码混淆(比较值)

[英]C program bad code confusion (compare values)

Just trying to compare two values in C, and find the smaller value.只是尝试比较 C 中的两个值,并找到较小的值。 Accidently did it in a really bad style, but I don't understand why C still let it run... the program didn't include the branch that two values are equal.不小心以一种非常糟糕的方式做了它,但我不明白为什么C仍然让它运行......程序没​​有包含两个值相等的分支。 But when it's given two equal values, it gives the program gives out the same value... may I ask what did C complier do?但是当它被赋予两个相等的值时,它给程序给出了相同的值......请问C编译器是做什么的? Thank you!谢谢! (the example below returns 3...) (下面的例子返回 3...)

int min(int x, int y);

int main(void)
{
    int a = 3, b = 3;
    printf("%d", min(a,b));
}

int min(int x, int y)
{
    if(x > y)
    return y;
}
    else if(x < y)
{
    return x;
}

Accidently did it in a really bad style, but I don't understand why C still let it run..不小心以一种非常糟糕的方式做了它,但我不明白为什么 C 仍然让它运行..

The program should not compile because this code该程序不应编译,因为此代码

int min(int x, int y)
{
    if(x > y)
    return y;
}
    else if(x < y)
{
    return x;
}

is syntactically incorrect.语法不正确。

This else statement这个 else 语句

    else if(x < y)
{
    return x;
}

is placed outside any function including min .放置在任何函数之外,包括min

It seems you mean看来你的意思

int min(int x, int y)
{
    if(x > y)
    {
        return y;
    }
    else if(x < y)
    {
        return x;
    }
}

But when it's given two equal values, it gives the program gives out the same value... may I ask what did C complier do?但是当它被赋予两个相等的值时,它给程序给出了相同的值......请问C编译器是做什么的?

The program has undefined behavior because the function min returns nothing when its two arguments are equal each other.该程序具有未定义的行为,因为当函数min的两个参数彼此相等时,它不返回任何内容。

From the C Standard (6.9.1 Function definitions)来自 C 标准(6.9.1 函数定义)

12 If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined. 12 如果到达终止函数的},并且调用者使用了函数调用的值,则行为未定义。

It should be defined for example the following way它应该被定义为例如以下方式

int min(int x, int y)
{
    return y < x ? y : x;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM