选择语句和对NULL的检查

时间:2018-01-26 04:38:08

标签: c pointers struct

我使用C语言进行编程,在定义struct后发现有些奇怪,然后尝试在main()中打印出一个字符串:

struct node{
  int value;
  struct node *next;
};

int main(){
  struct node test;
  test.value = 10;
  test.next = NULL;
  if(test.next->value > 100)
      printf("%s\n", "Big");
  return 0;
}

这个程序编译成功,但是在运行时我遇到了分段错误,我知道test.next->value是非法的test.next = NULL,如果这个分段错误可以避免。写得像这样:

if(test.next && test.next->value > 100) 
    printf("%s\n", "Big");

但现在它更难看了,我必须在其他程序中编写这种风格以避免段错误,让控制台只打印出来,是否有更好的方式来优雅地编写它? :)

3 个答案:

答案 0 :(得分:1)

没有

一些新语言的运算符仅在其左侧不为NULL时才会有所依赖,如果是,则返回NULL。例如,在C#中,

test.next?.value

相当于

test.next == null ? null : test.next.value

除了test.next只评估一次。

C没有这样的运营商。无论如何,它在这种情况下无济于事,因为您无法对null100进行数字比较。

答案 1 :(得分:1)

没有。 C没有您所寻求的语言功能。

C#确实有null conditional operator,但C没有。{/ p>

答案 2 :(得分:0)

我通常使用换行符和缩进来使它更漂亮,例如

if (test.next &&
    test.next->value > 100)
{
    printf("%s\n", "Big");
}

但总的来说,你会习惯这种语言,一旦你习惯它就不会那么难看。