logo

C의 Const 한정자

예선 const 값이 변경되지 않도록 지정하기 위해 변수 선언에 적용할 수 있습니다. 이는 const 변수가 저장된 위치에 따라 포인터를 사용하여 const 변수의 값을 변경할 수 있습니다. const를 변경하려고 시도하면 결과는 구현에 따라 정의됩니다.

일부 값이 일정하게 유지되고 실수로 수정되지 않도록 하려는 경우 C에서 const 한정자를 사용하는 것이 좋습니다.



C 프로그래밍에서 const 한정자는 다양한 동작을 제공하기 위해 다양한 컨텍스트에서 사용될 수 있습니다. 다음은 C에서 const 한정자의 몇 가지 다른 사용 사례입니다.

1. 상수 변수

const int var = 100;>

이 경우 const를 사용하여 변수를 선언합니다. ~였다 초기 값이 100인 상수입니다. 이 변수의 값은 초기화되면 수정할 수 없습니다. 다음 예를 참조하세요.




// C program to demonstrate that constant variables can not> // be modified> #include> int> main()> {> >const> int> var = 100;> >// Compilation error: assignment of read-only variable> >// 'var'> >var = 200;> >return> 0;> }>

>

>

산출

./Solution.cpp: In function 'int main()': ./Solution.cpp:11:9: error: assignment of read-only variable 'var' var = 200; ^>

2. 상수에 대한 포인터

const int* ptr;>

또는

int const *ptr;>

다른 정수 변수를 가리키도록 포인터를 변경할 수 있지만 포인터 ptr을 사용하여 가리키는 개체(엔티티)의 값을 변경할 수는 없습니다. 포인터는 읽기-쓰기 영역(현재 경우 스택)에 저장됩니다. 가리키는 개체는 읽기 전용 또는 읽기-쓰기 영역에 있을 수 있습니다. 다음 예를 살펴보겠습니다.

예시 1:




// C program to demonstrate that the pointer to point to> // any other integer variable, but the value of the object> // (entity) pointed can not be changed> #include> int> main(>void>)> {> >int> i = 10;> >int> j = 20;> >/* ptr is pointer to constant */> >const> int>* ptr = &i;> >printf>(>'ptr: %d '>, *ptr);> >/* error: object pointed cannot be modified> >using the pointer ptr */> >*ptr = 100;> >ptr = &j;>/* valid */> >printf>(>'ptr: %d '>, *ptr);> >return> 0;> }>

>

>

산출

./Solution.c: In function 'main': ./Solution.c:12:10: error: assignment of read-only location '*ptr' *ptr = 100; ^>

예제 2: 변수 i 자체가 상수인 프로그램.




// C program to demonstrate that the pointer to point to> // any other integer variable, but the value of the object> // (entity) pointed can not be changed> #include> int> main(>void>)> {> >/* i is stored in read only area*/> >int> const> i = 10;> >int> j = 20;> >/* pointer to integer constant. Here i> >is of type 'const int', and &i is of> >type 'const int *'. And p is of type> >'const int', types are matching no issue */> >int> const>* ptr = &i;> >printf>(>'ptr: %d '>, *ptr);> >/* error */> >*ptr = 100;> >/* valid. We call it up qualification. In> >C/C++, the type of 'int *' is allowed to up> >qualify to the type 'const int *'. The type of> >&j is 'int *' and is implicitly up qualified by> >the compiler to 'const int *' */> >ptr = &j;> >printf>(>'ptr: %d '>, *ptr);> >return> 0;> }>

>

>

산출

./Solution.c: In function 'main': ./Solution.c:18:10: error: assignment of read-only location '*ptr' *ptr = 100; ^>

다운 자격 C++에서는 허용되지 않으며 C에서 경고가 발생할 수 있습니다. 하향 제한은 정규화된 유형이 정규화되지 않은 유형에 할당되는 상황을 나타냅니다.

예 3: 자격을 보여주는 프로그램.

한 달에 몇 주가 있나요?




// C program to demonstrate the down qualification> #include> int> main(>void>)> {> >int> i = 10;> >int> const> j = 20;> >/* ptr is pointing an integer object */> >int>* ptr = &i;> >printf>(>'*ptr: %d '>, *ptr);> >/* The below assignment is invalid in C++, results in> >error In C, the compiler *may* throw a warning, but> >casting is implicitly allowed */> >ptr = &j;> >/* In C++, it is called 'down qualification'. The type> >of expression &j is 'const int *' and the type of ptr> >is 'int *'. The assignment 'ptr = &j' causes to> >implicitly remove const-ness from the expression &j.> >C++ being more type restrictive, will not allow> >implicit down qualification. However, C++ allows> >implicit up qualification. The reason being, const> >qualified identifiers are bound to be placed in> >read-only memory (but not always). If C++ allows> >above kind of assignment (ptr = &j), we can use 'ptr'> >to modify value of j which is in read-only memory.> >The consequences are implementation dependent, the> >program may fail> >at runtime. So strict type checking helps clean code.> >*/> >printf>(>'*ptr: %d '>, *ptr);> >return> 0;> }>

>

>

산출

main.c: In function ‘main’: main.c:16:9: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] 16 | ptr = &j; | ^ *ptr: 10 *ptr: 20>

3. 변수에 대한 상수 포인터

int* const ptr;>

위 선언은 정수 변수에 대한 상수 포인터입니다. 즉, 포인터가 가리키는 개체의 값을 변경할 수 있지만 포인터가 다른 변수를 가리키도록 변경할 수는 없습니다.




// C program to demonstrate that the value of object pointed> // by pointer can be changed but the pointer can not point> // to another variable> #include> int> main(>void>)> {> >int> i = 10;> >int> j = 20;> >/* constant pointer to integer */> >int>*>const> ptr = &i;> >printf>(>'ptr: %d '>, *ptr);> >*ptr = 100;>/* valid */> >printf>(>'ptr: %d '>, *ptr);> >ptr = &j;>/* error */> >return> 0;> }>

>

>

산출

./Solution.c: In function 'main': ./Solution.c:15:9: error: assignment of read-only variable 'ptr' ptr = &j; /* error */ ^>

4. 상수에 대한 상수 포인터

const int* const ptr;>

위 선언은 상수 변수에 대한 상수 포인터입니다. 즉, 포인터가 가리키는 값을 변경할 수 없으며 포인터가 다른 변수를 가리킬 수도 없습니다. 예를 들어 보겠습니다.




// C program to demonstrate that value pointed by the> // pointer can not be changed as well as we cannot point the> // pointer to other variables> #include> int> main(>void>)> {> >int> i = 10;> >int> j = 20;> >/* constant pointer to constant integer */> >const> int>*>const> ptr = &i;> >printf>(>'ptr: %d '>, *ptr);> >ptr = &j;>/* error */> >*ptr = 100;>/* error */> >return> 0;> }>

>

>

산출

./Solution.c: In function 'main': ./Solution.c:12:9: error: assignment of read-only variable 'ptr' ptr = &j; /* error */ ^ ./Solution.c:13:10: error: assignment of read-only location '*ptr' *ptr = 100; /* error */ ^>

C에서 const 한정자의 장점

C의 const 한정자는 다음과 같은 장점이 있습니다.

    향상된 코드 가독성: 변수를 const로 표시하면 다른 프로그래머에게 해당 값이 변경되어서는 안 된다는 점을 나타내므로 코드를 더 쉽게 이해하고 유지 관리할 수 있습니다. 향상된 유형 안전성: const를 사용하면 값이 실수로 수정되지 않도록 보장하여 코드에서 버그 및 오류가 발생할 가능성을 줄일 수 있습니다. 향상된 최적화: 컴파일러는 프로그램 실행 중에 해당 값이 변경되지 않는다는 것을 알고 있기 때문에 const 변수를 보다 효과적으로 최적화할 수 있습니다. 이를 통해 더 빠르고 효율적인 코드를 작성할 수 있습니다. 더 나은 메모리 사용량: 변수를 const로 선언하면 해당 값을 복사할 필요가 없어 메모리 사용량이 줄어들고 성능이 향상될 수 있습니다. 향상된 호환성: 변수를 const로 선언하면 const 변수를 사용하는 다른 라이브러리 및 API와 코드의 호환성을 높일 수 있습니다. 향상된 신뢰성: const를 사용하면 값이 예기치 않게 수정되지 않도록 보장하여 코드의 버그 및 오류 위험을 줄일 수 있으므로 코드의 신뢰성을 높일 수 있습니다.

요약

유형 선언 포인터 값 변경
(*포인트 = 100)
포인팅 값 변경
(포인트 = &a)
변수에 대한 포인터 정수 * ptr
상수에 대한 포인터 const int * ptr
int const * ptr
아니요
변수에 대한 상수 포인터 int * const ptr 아니요
상수에 대한 상수 포인터 const int * const ptr 아니요 아니요

이 기사는 다음에 의해 편집되었습니다. 나렌드라 캉랄카르 .