【问题标题】:Trying to understand the logic of an IF statement试图理解 IF 语句的逻辑
【发布时间】:2020-06-10 19:48:44
【问题描述】:

我正在尝试构建一些 Ada 代码,但要这样做,我必须了解一些 C。

在 net-snmp-5.8.1.pre2/apps/snmpbulkwalk.c 和可能的其他人中,有一个 if 声明,我试图了解正在发生的事情并将其分开,因此:

if ((vars->name_length < rootlen) || (memcmp(root, vars->name, rootlen * sizeof(oid))) != 0) {
   /*
    * not part of this subtree
    */
    running = 0;
    continue;
}

我得到name_length &lt; rootlen,我也得到memcpy 总是返回一个指针并且永远不会失败。从我可怜的视力看来,如果&lt; 失败,它会尝试总是成功的memcpy,然后执行 IF 块的内容。但是不...如果是这样,您可以将memcpy 放在块内。

无论我如何分离if 语句,我都无法让它按照已经编码的方式工作。

【问题讨论】:

  • memcpymemcmp?一个在代码中,另一个在您的问题中,但它们是不同的功能。
  • 天哪...我确实提到了我的视力不佳...

标签: c snmp


【解决方案1】:

您的if 进行“短路”评估。它基本上是这样的:

if (expression_A || expression_B)
    do_something;

它评估expression_A,如果它是trueexpression_B评估的。而且,if采用(即do_something 被执行)

如果expression_Afalse,则评估expression_B。如果 ittrue,则if采用

重述实际的if 代码:

if (vars->name_length < rootlen) {
   /*
    * not part of this subtree
    */
    running = 0;
    continue;
}

if (memcmp(root, vars->name, rootlen * sizeof(oid)) != 0) {
   /*
    * not part of this subtree
    */
    running = 0;
    continue;
}

重述一般情况:

if (expression_A)
    do_something;
else {
    if (expression_B)
        do_something;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多