조건에서 할당을 사용하는 이유는 무엇입니까?
많은 언어에서 할당은 조건에서 합법적입니다. 나는 그 이유를 결코 이해하지 못했습니다. 왜 다음과 같이 작성 하시겠습니까?
if (var1 = var2) {
...
}
대신에:
var1 = var2;
if (var1) {
...
}
if 문보다 루프에 더 유용합니다.
while( var = GetNext() )
{
...do something with var
}
그렇지 않으면 작성해야 할 것
var = GetNext();
while( var )
{
...do something
var = GetNext();
}
종종 오류 감지 등과 관련된 일련의 작업에서 가장 유용하다고 생각합니다.
if ((rc = first_check(arg1, arg2)) != 0)
{
report error based on rc
}
else if ((rc = second_check(arg2, arg3)) != 0)
{
report error based on new rc
}
else if ((rc = third_check(arg3, arg4)) != 0)
{
report error based on new rc
}
else
{
do what you really wanted to do
}
대안 (조건에서 할당을 사용하지 않음)은 다음과 같습니다.
rc = first_check(arg1, arg2);
if (rc != 0)
{
report error based on rc
}
else
{
rc = second_check(arg2, arg3);
if (rc != 0)
{
report error based on new rc
}
else
{
rc = third_check(arg3, arg4);
if (rc != 0)
{
report error based on new rc
}
else
{
do what you really wanted to do
}
}
}
장기간의 오류 검사를 사용하면 대안은 페이지의 RHS에서 벗어날 수 있지만 조건부 할당 버전은 그렇게하지 않습니다.
오류 검사는 단순히 검사가 아닌 '작업'( first_action()
,,) second_action()
일 수도 있습니다 third_action()
. 즉, 기능이 관리하는 프로세스의 단계를 확인할 수 있습니다. (대부분 내가 작업하는 코드에서 함수는 사전 조건 검사 줄이나 함수가 작동하는 데 필요한 메모리 할당 또는 유사한 줄을 따라 있습니다).
함수를 호출하는 경우 더 유용합니다.
if (n = foo())
{
/* foo returned a non-zero value, do something with the return value */
} else {
/* foo returned zero, do something else */
}
물론, n = foo (); 별도의 진술에서 if (n)이지만 위의 내용은 상당히 읽기 쉬운 관용구라고 생각합니다.
작업 할 데이터 나 오류를 나타내는 플래그 (또는 완료)를 반환하는 함수를 호출하는 경우 유용 할 수 있습니다.
다음과 같은 것 :
while ((c = getchar()) != EOF) {
// process the character
}
// end of file reached...
개인적으로 나는 그다지 좋아하지 않는 관용구이지만 때로는 대안이 더 추악합니다.
GCC can help you detect (with -Wall) if you unintentionally try to use an assignment as a truth value, in case it recommends you write
if ((n = foo())) {
...
}
I.e. use extra parenthesis to indicate that this is really what you want.
The idiom is more useful when you're writing a while
loop instead of an if
statement. For an if
statement, you can break it up as you describe. But without this construct, you would either have to repeat yourself:
c = getchar();
while (c != EOF) {
// ...
c = getchar();
}
or use a loop-and-a-half structure:
while (true) {
c = getchar();
if (c == EOF) break;
// ...
}
I would usually prefer the loop-and-a-half form.
The short answer is that Expression-oriented programming languages allow more succinct code. They don't force you to separate commands from queries.
In PHP, for example, it's useful for looping through SQL database results:
while ($row = mysql_fetch_assoc($result)) {
// Display row
}
This looks much better than:
$row = mysql_fetch_assoc($result);
while ($row) {
// Display row
$row = mysql_fetch_assoc($result);
}
The other advantage comes during the usage of gdb. In the following code the error code is not known if we were to single step.
while (checkstatus() != -1) {
// process
}
Rather
while (true) {
int error = checkstatus();
if (error != -1)
// process
else
//fail
}
Now during single step we can know what was the return error code from the checkstatus().
The reason is :
Performance improvement (Sometimes)
Lesser Code (Always)
Take an example: There is a method someMethod()
and in an if
condition you want to check whether the return value of the method is null
. If not you are going to use the return value again.
If(null != someMethod()){
String s = someMethod();
......
//Use s
}
It will hamper the performance since you are calling the same method twice. Instead use:
String s;
If(null != (s = someMethod())) {
......
//Use s
}
참고URL : https://stackoverflow.com/questions/151850/why-would-you-use-an-assignment-in-a-condition
'Program Tip' 카테고리의 다른 글
모든 TypeScript 소스를보고 컴파일하는 방법은 무엇입니까? (0) | 2020.11.10 |
---|---|
데이터베이스에서 csv 파일로 테이블 내보내기 (0) | 2020.11.10 |
두 날짜의 날짜 정보가 동일한 지 확인 (0) | 2020.11.09 |
Rails의 link_to 본문에 포함 된 HTML (0) | 2020.11.09 |
내 C ++ 코드에서 printf를 사용해야합니까? (0) | 2020.11.09 |