C ++ 03에서 'auto'키워드를 사용하는 이유가 있습니까?
참고 이 질문에 C ++ (11)이 비준되기 전에 원래 2009에 게시했습니다과의 의미 전에
auto
키워드 대폭 변경되었습니다. 제공된 답변 은 자동 유형 추론 의 C ++ 11 의미가 아니라 지정된 스토리지 클래스 라는 C ++ 03 의미 에만 관련 됩니다 . C ++ 11 사용시기에 대한 조언을 찾고 있다면 이 질문은 해당 질문과 관련이 없습니다.auto
auto
auto
오랫동안 static
C 에서 키워드 를 사용할 이유가 없다고 생각했습니다. 블록 범위 외부에서 선언 된 변수는 암시 적으로 전역 적이기 때문입니다. 그런 다음 static
블록 범위 내 에서 변수를 선언 하면 영구 기간이 제공되고 블록 범위 외부 (프로그램 범위 내)로 선언하면 파일 범위 (컴파일 단위에서만 액세스 할 수 있음)가 제공된다는 것을 발견했습니다.
그래서 이것은 내가 (아마도) 아직 완전히 이해하지 못하는 하나의 키워드만을 남깁니다 : auto
키워드. '로컬 변수'외에 다른 의미가 있습니까? 당신이 그것을 사용하고 싶을 때 당신을 위해 암묵적으로 수행되지 않는 것이 무엇입니까? auto
변수는 프로그램 범위에서 어떻게 작동합니까? static auto
파일 범위 의 변수는 무엇입니까 ? 이 키워드는 완전성을 위해 존재 하는 것 외에 다른 목적을 가지고 있습니까?
auto
스토리지 클래스 지정자입니다, static
, register
및 extern
도. 선언에서이 네 가지 중 하나만 사용할 수 있습니다.
지역 변수 (가없는 static
)는 자동 저장 기간을 가지며, 이는 정의 시작부터 블록 끝까지 존재 함을 의미합니다. 어쨌든 기본값이기 때문에 자동을 앞에 두는 것은 중복됩니다.
나는 그것을 C ++에서 사용하는 이유를 모른다. 암시 적 int 규칙이있는 이전 C 버전에서는 다음과 같이이를 사용하여 변수를 선언 할 수 있습니다.
int main(void) { auto i = 1; }
유효한 구문을 만들거나 case i
가 범위 내에있는 경우 할당 식에서 명확하게하기 위해 . 그러나 이것은 어쨌든 C ++에서 작동하지 않습니다 (유형을 지정해야합니다). 재미있게도 C ++ 표준은 다음과 같이 씁니다.
블록 범위에서 스토리지 클래스 지정자없이 선언되거나 함수 매개 변수로 선언 된 객체는 기본적으로 자동 저장 기간을 갖습니다. [참고 : 따라서 자동 지정자는 거의 항상 중복되며 자주 사용되지 않습니다. auto의 한 가지 용도는 선언문을 표현 문 (6.8)과 명시 적으로 구별하는 것입니다. — 끝 참고]
그 중 캐스팅이 될 수있는 다음과 같은 시나리오를 의미 a
하는 int
나 변수의 선언 a
유형의 int
주위에 여분의 괄호를 가지고 a
. 항상 선언으로 간주되므로 auto
여기에 유용한 정보를 추가하지 않고 대신 인간을위한 것입니다. 그러나 다시 말하지만 인간은 주위의 중복 괄호를 제거하는 것이 더 나을 a
것입니다.
int(a);
auto
C ++ 0x와 함께 도착 하는 새로운 의미로 인해 코드에서 C ++ 03의 의미와 함께 사용하지 않는 것이 좋습니다.
C ++ 11에서는 auto
새로운 의미가 있습니다. 변수 유형을 자동으로 추론 할 수 있습니다.
그게 왜 유용할까요? 기본적인 예를 살펴 보겠습니다.
std::list<int> a;
// fill in a
for (auto it = a.begin(); it != a.end(); ++it) {
// Do stuff here
}
는 auto
타입의 반복자가 만들어집니다 std::list<int>::iterator
.
이렇게하면 심각하게 복잡한 코드를 훨씬 쉽게 읽을 수 있습니다.
다른 예시:
int x, y;
auto f = [&]{ x += y; };
f();
f();
거기에서 auto
람다 식을 변수에 저장하는 데 필요한 유형을 추론했습니다. Wikipedia는 주제에 대해 잘 다루고 있습니다.
auto 키워드는 현재 아무런 목적이 없습니다. 지역 변수의 기본 스토리지 클래스를 다시 작성하는 것이 맞습니다 static
. 정말 유용한 대안은 .
그것은 C ++ 0x에서 새로운 의미 를 가지고 있습니다. 그것은 당신에게 그것이 얼마나 쓸모 없는지에 대한 아이디어를 제공합니다!
GCC는 auto
중첩 된 함수 를 위해 특별한 용도로 사용 됩니다 . 여기를 참조 하십시오 .
정의 전에 호출하려는 중첩 함수가있는 경우 auto
.
"auto"는 컴파일러에게 변수 (메모리 또는 레지스터)를 넣을 위치를 스스로 결정하도록 지시합니다. 그것의 아날로그는 "레지스터"인데, 이것은 컴파일러에게 레지스터에 그것을 유지하도록 지시하는 것으로 추정됩니다. 현대 컴파일러는 둘 다 무시하므로 여러분도 그렇게해야합니다.
I use this keyword to explicitly document when it is critical for function, that the variable be placed on the stack, for stack-based processors. This function can be required when modifying the stack prior to returning from a function (or interrupt service routine). In this case I declare:
auto unsigned int auiStack[1]; //variable must be on stack
And then I access outside the variable:
#define OFFSET_TO_RETURN_ADDRESS 8 //depends on compiler operation and current automatics
auiStack[OFFSET_TO_RETURN_ADDRESS] = alternate_return_address;
So the auto
keyword helps document the intent.
According to Stroustrup, in "The C Programming Language" (4th Edition, covering C 11), the use of 'auto' has the following major reasons (section 2.2.2) (Stroustrup words are quoted):
1)
The definition is in a large scope where we want to make the type clearly visible to readers of our code.
With 'auto' and its necessary initializer we can know the variable's type in a glance!
2)
We want to be explicit about variable's range or precision (e.g., double rather than float)
In my opinion a case that fits here, is something like this:
double square(double d)
{
return d*d;
}
int square(int d)
{
return d*d;
}
auto a1 = square(3);
cout << a1 << endl;
a1 = square(3.3);
cout << a1 << endl;
3)
Using 'auto' we avoid redundancy and writing long type names.
Imagine some long type name from a templatized iterator:
(code from section 6.3.6.1)
template<class T> void f1(vector<T>& arg) {
for (typename vector<T>::iterator p = arg.begin(); p != arg.end(); p)
*p = 7;
for (auto p = arg.begin(); p != arg.end(); p)
*p = 7;
}
In old compiler, auto was one way to declare a local variable at all. You can't declare local variables in old compilers like Turbo C without the auto keyword or some such.
The new meaning of the auto keyword in C++0x is described very nicely by Microsoft's Stephan T. Lavavej in a freely viewable/downloadable video lecture on STL found at MSDN's Channel 9 site here.
The lecture is worth viewing in its entirety, but the part about the auto keyword is at about the 29th minute mark (approximately).
Is there some other meaning to 'auto' other than 'local variable?'
Not in C++03.
Anything it does that isn't implicitly done for you wherever you may want to use it?
Nothing whatsoever, in C++03.
How does an auto variable behave in program scope? What of a static auto variable in file-scope?
Keyword not allowed outside of a function/method body.
Does this keyword have any purpose [in C++03] other than just existing for completeness?
Surprisingly, yes. C++ design criteria included a high degree of backward compatibility with C. C had this keyword and there was no real reason to ban it or redefine its meaning in C++. So, the purpose was one less incompatibility with C.
Does this keyword have any purpose in C other than just existing for completeness?
I learned one only recently: ease of porting of ancient programs from B. C evolved from a language called B whose syntax was quite similar to that of C. However, B had no types whatsoever. The only way to declare a variable in B was to specify its storage type (auto
or extern
). Like this:
auto i;
This syntax still works in C and is equivalent to
int i;
because in C, the storage class defaults to auto
, and the type defaults to int
. I guess that every single program that originated in B and was ported to C was literally full of auto
variables at that time.
C++03 no longer allows the C style implicit int, but it preserved the no-longer-exactly-useful auto
keyword because unlike the implicit int, it wasn't known to cause any trouble in the syntax of C.
참고URL : https://stackoverflow.com/questions/1046477/is-there-any-reason-to-use-the-auto-keyword-in-c03
'program tip' 카테고리의 다른 글
화면 하단에서 레이아웃을 위로 슬라이드 (0) | 2020.09.18 |
---|---|
Laravel Eloquent "IN"쿼리를 만드는 방법은 무엇입니까? (0) | 2020.09.18 |
Eclipse 프로젝트에서 일부 폴더를 제외하려면 어떻게해야합니까? (0) | 2020.09.18 |
벡터 변환 (0) | 2020.09.18 |
시간 초과 후 작업을 중단하는 ExecutorService (0) | 2020.09.17 |