Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# if else语句格式_C#_C++ - Fatal编程技术网

C# if else语句格式

C# if else语句格式,c#,c++,C#,C++,也许有同样的问题,但我不知道如何表述。 这两者之间有什么区别吗 int x = 0; if( someCondition ) { x = 1; } 及 像这样的小问题很容易在godbolt这样的在线编译器上测试: int test1(bool someCondition) { int x = 0; if( someCondition ) { x = 1; } return x; } int test2(bool someCondition) { int

也许有同样的问题,但我不知道如何表述。 这两者之间有什么区别吗

int x = 0;
if( someCondition )
{
    x = 1;
}


像这样的小问题很容易在godbolt这样的在线编译器上测试:

int test1(bool someCondition)
{
  int x = 0;
  if( someCondition )
  {
    x = 1;
  }
  return x;
}

int test2(bool someCondition)
{
  int x;
  if( someCondition )
  {
    x = 1;
  }
  else
  {
    x = 0;
  }
  return x;
}

int test3(bool someCondition)
{
  return someCondition ? 1 : 0;
}

int test4(bool someCondition)
{
  return int(someCondition);
}
结果汇编程序:

test1(bool):
        movzx   eax, dil
        ret
test2(bool):
        movzx   eax, dil
        ret

test3(bool):
        movzx   eax, dil
        ret
test4(bool):
        movzx   eax, dil
        ret

所以,实际上不是。这只是风格的问题。

编译器足够聪明,能够理解它是完全相同的,并且将生成相同的代码


区别在于可读性和可维护性;如果你有两个版本作为一个更大的程序的一部分,它应该反映所做的事情的逻辑概念。

两者都会做同样的事情。没有技术上没有区别,除了总是喜欢初始化变量(在c#IIRC中不是必需的)。结果是一样的,但在性能或其他方面有任何区别吗?@Mažas“但在性能或其他方面有任何差异吗?”您必须首先选择一种语言,以合理地回答这一问题。选择一种语言…?@受影响在测试之前将变量设置为零有一个隐含的其他因素。有兴趣的人请链接到godbolt:
test1(bool):
        movzx   eax, dil
        ret
test2(bool):
        movzx   eax, dil
        ret

test3(bool):
        movzx   eax, dil
        ret
test4(bool):
        movzx   eax, dil
        ret