嵌套if(条件)和逻辑运算符之间的区别

问题描述 投票:0回答:1

嵌套if(条件)和逻辑运算符在性能和逻辑方面有什么区别。

if(a && b && c){
 //do something 
 }

if(a){
   if(b){
         if(c){
       //do something
     }
   }
 }

以上代码是否与逻辑明智相同?我主要担心的是代码的性能,性能明智,最好用吗?

performance if-statement logic operator-keyword logical-operators
1个回答
0
投票

如果您尝试将这两个代码转换为assembly语言(非常接近机器语言),则两个代码将完全相同(first codesecond code):

C:

void Main(){
    int a=1, b=2, c= 3, res = 0;

    if(a && b && c)
        res = 100;
}

// or
void Main(){
    int a=1, b=2, c= 3, res = 0;

    if(a)
        if(b)
            if(c)
                res = 100;
}

装配输出:

Main():
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], 1
        mov     DWORD PTR [rbp-8], 2
        mov     DWORD PTR [rbp-12], 3
        mov     DWORD PTR [rbp-16], 0
        cmp     DWORD PTR [rbp-4], 0
        je      .L3                     ; jump to the end if `a` is not true
        cmp     DWORD PTR [rbp-8], 0
        je      .L3                     ; jump to the end if `b` is not true
        cmp     DWORD PTR [rbp-12], 0
        je      .L3                     ; jump to the end if `c` is not true
        mov     DWORD PTR [rbp-16], 100 ; otherwise do something
.L3:
        nop
        pop     rbp
        ret
© www.soinside.com 2019 - 2024. All rights reserved.