C ++에서 증가-언제 x ++ 또는 ++ x를 사용합니까?
저는 현재 C ++를 배우고 있으며 얼마 전에 증가에 대해 배웠습니다. "++ x"를 사용하여 이전에 증분을 만들고 "x ++"를 사용하여 이후에 할 수 있다는 것을 알고 있습니다.
그래도 언제 둘 중 하나를 사용해야할지 모르겠습니다. "++ x"를 실제로 사용하지 않았고 지금까지 모든 것이 잘 작동했습니다. 언제 사용해야합니까?
예 : for 루프에서 "++ x"를 사용하는 것이 좋을 때는 언제입니까?
또한 누군가 다른 증가 (또는 감소)가 어떻게 작동하는지 정확히 설명 할 수 있습니까? 정말 감사하겠습니다.
선호도의 문제가 아니라 논리의 문제입니다.
x++
현재 명령문 을 처리 한 후 변수 x의 값을 증가시킵니다 .
++x
현재 명령문을 처리 하기 전에 변수 x의 값을 증가시킵니다 .
따라서 작성하는 논리를 결정하십시오.
x += ++i
i를 증가시키고 i + 1을 x에 추가합니다. x += i++
x에 i를 더한 다음 i를 증가시킵니다.
Scott Meyers 는 논리가 접미사가 적절하다고 지시하는 경우를 제외하고 접두사를 선호하라고 말합니다.
"더 효과적인 C ++"항목 # 6- 저에게 충분한 권한입니다.
책을 소유하지 않은 사람들을 위해 관련 인용문이 있습니다. 32 페이지에서 :
C 프로그래머로 일하던 시절부터 증분 연산자의 접두어 형식을 "증가 및 가져 오기"라고 부르는 반면 접미어 형식은 "가져 오기 및 증분"이라고도합니다. 두 구절은 모두 형식적인 사양으로 작동하기 때문에 기억해야합니다.
34 페이지 :
효율성을 걱정하는 사람이라면 접미사 증가 기능을 처음 보았을 때 땀을 흘렸을 것입니다. 이 함수는 반환 값에 대한 임시 객체를 생성해야하며 위의 구현은 생성 및 소멸되어야하는 명시 적 임시 객체도 생성합니다. 접두사 증가 함수에는 그러한 임시가 없습니다 ...
반복자를 증가 시킬 때 cppreference 에서 :
이전 값을 사용하지 않으려면 사전 증가 연산자 (++ iter)를 사후 증가 연산자 (iter ++)보다 선호해야합니다. 사후 증가는 일반적으로 다음과 같이 구현됩니다.
Iter operator++(int) {
Iter tmp(*this); // store the old value in a temporary object
++*this; // call pre-increment
return tmp; // return the old value }
분명히 사전 증가보다 효율성이 떨어집니다.
사전 증가는 임시 개체를 생성하지 않습니다. 개체를 만드는 데 비용이 많이 드는 경우 이는 상당한 차이를 만들 수 있습니다.
시맨틱 (사전 / 사후)이 중요하지 않은 사전 / 사후 증분을 사용하는 경우 생성 된 코드가 동일하게 공격된다는 사실을 알고 싶습니다.
예:
pre.cpp :
#include <iostream>
int main()
{
int i = 13;
i++;
for (; i < 42; i++)
{
std::cout << i << std::endl;
}
}
post.cpp :
#include <iostream>
int main()
{
int i = 13;
++i;
for (; i < 42; ++i)
{
std::cout << i << std::endl;
}
}
_
$> g++ -S pre.cpp
$> g++ -S post.cpp
$> diff pre.s post.s
1c1
< .file "pre.cpp"
---
> .file "post.cpp"
명심해야 할 가장 중요한 점은 imo입니다. x ++는 실제로 증가가 발생하기 전에 값을 반환해야하므로 객체의 임시 복사본을 만들어야합니다 (사전 증가). 제자리에서 증분되어 반환되는 ++ x보다 효율성이 떨어집니다.
Another thing worth mentioning, though, is that most compilers will be able to optimize such unnecessary things away when possible, for instance both options will lead to same code here:
for (int i(0);i<10;++i)
for (int i(0);i<10;i++)
I agree with @BeowulfOF, though for clarity I would always advocate splitting the statements so that the logic is absolutely clear, i.e.:
i++;
x += i;
or
x += i;
i++;
So my answer is if you write clear code then this should rarely matter (and if it matters then your code is probably not clear enough).
Just wanted to re-emphasize that ++x is expected to be faster than x++, (especially if x is an object of some arbitrary type), so unless required for logical reasons, ++x should be used.
You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.
An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.
Edit: fixed the mixup of prefix and suffix notation
Understanding the language syntax is important when considering clarity of code. Consider copying a character string, for example with post-increment:
char a[256] = "Hello world!";
char b[256];
int i = 0;
do {
b[i] = a[i];
} while (a[i++]);
We want the loop to execute through encountering the zero character (which tests false) at the end of the string. That requires testing the value pre-increment and also incrementing the index. But not necessarily in that order - a way to code this with the pre-increment would be:
int i = -1;
do {
++i;
b[i] = a[i];
} while (a[i]);
It is a matter of taste which is clearer and if the machine has a handfull of registers both should have identical execution time, even if a[i] is a function that is expensive or has side-effects. A significant difference might be the exit value of the index.
Postfix form of ++,-- operator follows the rule use-then-change ,
Prefix form (++x,--x) follows the rule change-then-use.
Example 1:
When multiple values are cascaded with << using cout then calculations(if any) take place from right-to-left but printing takes place from left-to-right e.g., (if val if initially 10)
cout<< ++val<<" "<< val++<<" "<< val;
will result into
12 10 10
Example 2:
In Turbo C++, if multiple occurrences of ++ or (in any form) are found in an expression, then firstly all prefix forms are computed then expression is evaluated and finally postfix forms are computed e.g.,
int a=10,b;
b=a++ + ++a + ++a + a;
cout<<b<<a<<endl;
It's output in Turbo C++ will be
48 13
Whereas it's output in modern day compiler will be (because they follow the rules strictly)
45 13
- Note: Multiple use of increment/decrement operators on same variable in one expression is not recommended. The handling/results of such
expressions vary from compiler to compiler.
참고URL : https://stackoverflow.com/questions/1812990/incrementing-in-c-when-to-use-x-or-x
'IT박스' 카테고리의 다른 글
angular ng-if 또는 ng-show가 느리게 응답합니다 (2 초 지연?) (0) | 2020.09.24 |
---|---|
괜찮은 C # 프로파일 러가 있습니까? (0) | 2020.09.24 |
PHP의 오류 로그는 XAMPP에서 어디에 있습니까? (0) | 2020.09.24 |
문자열을 날짜 T-SQL로 변환하는 방법은 무엇입니까? (0) | 2020.09.24 |
Javascript / jQuery에서 (e)는 무엇을 의미합니까? (0) | 2020.09.24 |