0% found this document useful (0 votes)
43 views7 pages

Const

explanation of the const keyword for c programming

Uploaded by

Viraat Sewraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
43 views7 pages

Const

explanation of the const keyword for c programming

Uploaded by

Viraat Sewraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 7
= oS Q Const Qualifier in C Read Diseus\70+) Courses Practice ‘The qualifier const can be applied to the deciaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation defined if an attempt is made to change a const. Using the const qualifier in C is a good practice when we want to ensure that some values should remain constant and should not be accidentally modified. In C programming, the const qualifier can be used in different contexts to provide various behaviors. Here are some different use cases of the const qualifier in C: 1. Constant Variables const int var = 100; In this case, consts used to declare a variable var as a constant with an intial value of 100. The value of this variable ‘cannot be modified once iti initialized, See the following example: o DE ‘ester iow Programming Complete Beginner toAdvonced EET 11 © program to demonstrate that constant variables can not 1/ be modified sot main) « const int var = 168; 11 Comphiation exror: asstgnnent of read-only varsabie War’ Output -/Solution.cpp: In function “int matn()*: /Solution.cpp:11:9: error: assignaent of read-only variable ‘var’ var = 2005 TrendingNow —ataStrctures Algorithms TopicwisePractice Python MachineLearning DataScience JavaScript Java WebDevelopment Soot const int* ptr; oO on i gmnnaeiornate dns Ant const *ptes We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case). The object pointed may be in the read-only or read-write area, Let us see the following examples Example 1: c ]D 11 program to denonstrate that the pointer to point to 1/ any other integer variable, but the value of the object 11 (entity) pointes can not be changed include int main(void) « {* per As pointer to constant */ Const tnt? ptr = 8i; princf(*ptr: Rela", *ptr)s 7° error: object pointed cannot be modified Using the pointes ptr */ sptr = 100; ptr = aj; /* volts */ printr(*ptrs Bé\n", *ptr)s Output -/Solution.c: In function ‘main' -/Solution.c:12:10: error: assignment of read-only location ‘*ptr’ sper = 100; Example 2: Program where variable i itself is constant. c © 11.¢ program to denonstrate that the pointer to point to 11 any other integer variable, but the value of the object 11 (entity) peintes can not be changed Ant main(void) ‘ (94 fs stoned in read only areat/ int const 1 = 18; sot f= 20) J* pointer to integer constant. Here 4 45 of type “const int", anal is of type “const int *". And p 18 of type const int", types are matching so issue */ int const® ptr = 815 prinef("ptrs Bé\n"s *ptr)s 19 error */ ptr = 100; /* valid. We cal1 At up qualification. In Cicer, the type of “int ** Ss allowed to up qualify to the type “const int *". The type of on i gmnnaeiornate dns Ay ds Tint +7 and ds implicitly up qualified by ‘the compiler to "const int *” */ S ma\n", speeds > Output -/Solution.c: In funetion ‘main’ -/Solution.c:18:10: error: assignment of read-only location “*ptr’ sptr = 109; Down qualification is not allowed in C++ and may cause warnings in C. Down qualification refers to the situation where a qualified type is assigned to a non-qualified type, Example 3: Program to show down qualification. c ]D 11 program to denonstrate the down qualification O sinclude «stéio.t> Dine matn(vosay ‘ int = 205 int const j = 20; {9 per is pointing an integer object */ nt™ pte primes fers d\n", ptr) /* the below assignment is invalid in Ces, results in error in ¢, the conpiler *nay* throw a warning, but casting is implicitly allowed */ per = 83; (9 tn CH, Ht As called “down qualification’. the type of expression &j 1s “coast int *" ang the type of pr is “int *7. The assignment “ptr = 8" causes to inplicitly repove const-ness. from the expression &. Coe being nore type restrictive, will not allow Iinplicit doan qualification. However, C++ allows implicit up qualification. The reason being, const qualified identifiers are bound ¢9 be placed in read-only nenory (but not always). If Cr+ allows above kind of assignment (ptr = 8j), we can use ‘ptr’ to nodify value of 3 which 4s in reaé-only senory. The consequences are inplenentation dependent, tne progran nay fail at runtine. So strict type checking helps clean code. ” prineh("epte: d\n", *ptr)s ) Output fsein.c: In function ‘main’: ain. warning: assignment discards ‘const’ qualifier fron pointer target type [-Wéiscarded- qualifiers) a6 | ptr = 845 on i gmnnaeiornate dns spte: 10 sptr: 20 3. Constant Pointer to Variable Ant const ates ‘The above declaration is @ constant pointer to an integer variable, which means we can change the value of the object pointed by the pointer, but cannot change the pointer to point to another variable Example c © 11 program to denonstrate that the value of object pointed 1/ by pointer can be changed bet the pointer can not point 11 20 another varisble include sn main(void) ‘ int £ = 205 int j= 285 1° constant pointer to integer */ fint® const ptr = &is operas ‘ptr = 400; /* valid */ printf(*ptr: 2é\n", *ptr)s ptr = 83; /* ervor +7 return 8; Output -/Solution.c: In function ‘main' /Solution.c:15:9: error: assignment of read-only variable ‘pts’ ptr = 8; /* erron */ 4, Constant Pointer to Constant const int* const ptr: ‘The above declaration is a constant pointer to a constant variable which means we cannot change the value pointed by the pointer as well as we cannot point the pointer to other variables. Let us see with an example. c © 11 program to denonstrate that valve pointed by the 1/ pointer can not be changed as Well as we cannot point the 11 pointer to other variables include Ant mate(votd) « int § = 20 int J = 205 {* constant pointer to constant integer */ const int* const ptr = Ais on i gmnnaeiornate dns peinef(*ptes xa\a", ¢ptr)s ptr = 835 /* ervor +7 “ptr = 100; /* error */ > Output -/solution.c: In funetion ‘main’ -/Solution.c:12:9: error: assignment of read-only variable ‘ptr r= aj; /* error */ -/Solution.€:13:18: error: assignment of read-only location “*ptr sptr = 100; /* error */ Advantages of const Qualifiers in C ‘The const qualifier in C has the following advantages: ‘+ Improved Code Readability: By marking a variable as const, you indicate to other programmers that its value should not be changed, making your code easier to understand and maintain, + Enhanced Type Safety: By using const, yau can ensure that values are net accidentally modified, reducing the chance fof bugs and errors in your code. + Improved Optimization: Compilers can optimize const variables more effectively as they know that their values will not change during program execution. This can resutt in faster and mare efficient code. ‘+ Better Memory Usage: By declaring variables as const, you can often avoid having to make a copy of their values, which can reduce memory usage and improve performance. ‘+ Improved Compatibility: By declaring variables as const, you can make your code more compatible with other Libraries and APIs that use const variables, + Improved Relial modified unexpectedly, reducing the risk of bugs and errors in your code, ity: By using const, you can make your cade more reliable, as you can ensure that values are nat Summary Type Declaration Pointer Value Change Pointing Value Change (*ptr = 100) (ptr = &) Pointer to Variable int ptr Yes Yes const int "ptr Pointer to Constant No Yes int const * ptr Constant Pointer to Variable int * const ptr Yes No Constant Pointer to Constant _constint* const ptr No No ‘This article is compiled by “Narendra Kangralkar” Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Last Undated 07 Aug, 2022 Oo 0 & Previous Next > Constants in ¢ Article Contributed 8 8 eeksforGeeks Article Tags: ‘company outs Leal carers Inmedia avertiewithus compus raining Program ‘Computer Science Computer Network Databace Management Software Fnginering Digtal Lop Design Engineeringaths Interview Corner company Wise Preparation Explore JobeActhon Hing Hacka.Thon (te Week Contest oftine clases {DetincR) skin vac Master Systam Design Python Python Programming Django Tutorial Python Projets Python Thnter ‘open Python Tuoi Python Interview ‘question GfG School CBSE Notes for Class (CBSE Notes for clase on i gmnnaeiornate dns Different ways to declare variable as constant in C Vote for difficulty Creer sifcutty Mesum Storage Classes and Type Qualifiers, pointer, CLanguage DG GeeksforGeeks © Tomer, Sector Wolo 1B teedbackegerstorgeetsorg 00080 Ss es Languages Python oe Pap otarg sou Language roi Toto Data Science & ML. Python Beginner Machine earing Tutor Maths For Machine Panda Tetoria NumPy Tato NUP Tutor Deep Learning Tatar Commerce ecountaney busines Studies DSA Concepts Strings inka st Algorthms searching Sorting athemat Devops Docker upsc Polity Notes Geography Notes DSA Roadmaps DsAler Beginners asic SA Coding Problems sa Resemap by Sandeep Jon ‘Top 100 DSA ntervew Problems competitive Programming ‘Top osaforcP ‘op soTree Problems ‘op 50Graph Problems “Top so‘ray Problems “Top SoSting Problems ‘Top S0DP Problems Top 1s Websites or cP SSSC/ BANKING SSCCGL Syllabus 810 sylabus and C++ ‘Web Development JavaScript Bootstrap anguacss Nodels boressis Ledaeh System Design Scalabittyin so Low Level Design or tub Questions Write & Earn Write an ate Improvean Ace Prparation or SOE ‘eerienced Interviews Invemshipinterviws Competitive Programming ‘Aptitude Preparation (CBSE Notes for lass 10 (CBSE Notes for Clase12 (CASE Notes for class 12 Engish Grammar on i gmnnaeiornate dns Economies Human Resource Management (HRM) Management Income Tax Finance Statistics for Economics History Notes Science and Technology Important Topisin ethics sel clerk sabes InP Po sylabus 15 cer sylabus aptitude questions SSC COL Proctice Papers Pick Topesto write Weitentervew Intarnships

You might also like