简体   繁体   English

那个条件是什么意思?

[英]What does it mean that condition?

What should this current -> yes evaluate in if condition?这个current -> yes在 if 条件下应该评估什么? (It's not complete code you can assume any question in yes) (这不是完整的代码,您可以假设是的任何问题)

typedef struct node {
    char *question;
    struct node *no;
    struct node *yes;
} node;

node *current;

if (current->yes) {
    current = current->yes;
}

Thanks a lot for helping非常感谢您的帮助

这意味着如果current->yes不是0 (不是空指针)。

You're getting the address of yes member of type struct node * , by dereferencing current object.通过取消引用current对象,您将获得struct node *类型的yes成员的地址。 Which is, if allocated the memory properly, it'll be non zero, and if not it'll be 0 or NULL .也就是说,如果正确分配内存,它将是非零,如果不是,它将是 0 或NULL For example memory allocations can fail.例如,内存分配可能会失败。

So, basically the condition: if (current->yes) { ... } checks whether memory is allocated properly or not.所以,基本上是条件: if (current->yes) { ... }检查内存分配是否正确。

The following code :以下代码:

if (current->yes) {
    current = current->yes;
}

is equivalent to相当于

if (current->yes != NULL) {
    current = current->yes;
}

So the condition is checking yes to not be NULL pointer所以条件是检查是不是空指针

The if() construct in C is defined to evaluate its argument and compare it to 0 . C 中的if()构造被定义为评估其参数并将其与0进行比较。 As such, if(foo) is always equivalent to if(foo != 0) or if(foo != NULL) , considering that NULL compares equal to 0 .因此,考虑到NULL比较等于0if(foo)总是等价于if(foo != 0)if(foo != NULL)

Or, put another way, if(myPointer) checks whether the pointer points to a valid object.或者,换句话说, if(myPointer)检查指针是否指向有效对象。 This is a very common idiom in C programming.这是 C 编程中非常常见的习语。


This is true even if you write if(a == b) .即使您编写if(a == b)也是如此。 This is fully equivalent to if((a == b) != 0) : The value of a == b is either 0 for false or 1 for true, and that result is then compared to 0 by the abstract machine to determine which branch to execute.这完全等同于if((a == b) != 0)a == b值要么是0表示假,要么是1表示真,然后抽象机将结果与0进行比较以确定哪个分支来执行。 Obviously, compilers will directly use the result of the comparison in if(a == b) , because that's equivalent to producing the 1 or 0 and then comparing a second time to 0 .显然,编译器将直接使用if(a == b)中的比较结果,因为这相当于产生10然后第二次与0进行比较。 However, the language is defined with the extra comparison against 0 to make it fully agnostic about what kind of expression is used within the parentheses.但是,语言是通过与0的额外比较来定义的,以使其完全不知道括号内使用的是哪种表达式。 All the language cares about is that the resulting value is comparable to 0 .所有语言关心的是结果值是否与0相当。

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

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