Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
43 views
7 pages
Const
explanation of the const keyword for c programming
Uploaded by
Viraat Sewraj
AI-enhanced title
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
Download
Save
Save const For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
43 views
7 pages
Const
explanation of the const keyword for c programming
Uploaded by
Viraat Sewraj
AI-enhanced title
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
Carousel Previous
Carousel Next
Download
Save
Save const For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 7
Search
Fullscreen
= 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 dnsAnt 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 dnsAy 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 dnsspte: 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 dnspeinef(*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 AcePrparation 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
Programme Specification: BSC (Hons) Information Technology
PDF
No ratings yet
Programme Specification: BSC (Hons) Information Technology
11 pages
Using Const in C
PDF
No ratings yet
Using Const in C
4 pages
Pointers and Const: by Alex, On July 16Th, 2007
PDF
No ratings yet
Pointers and Const: by Alex, On July 16Th, 2007
2 pages
Volatile
PDF
No ratings yet
Volatile
1 page
C - Constants
PDF
No ratings yet
C - Constants
5 pages
1998-08 What Const Really Means PDF
PDF
No ratings yet
1998-08 What Const Really Means PDF
3 pages
What Const Really Means
PDF
No ratings yet
What Const Really Means
3 pages
Const Pointer
PDF
No ratings yet
Const Pointer
7 pages
Concept of Pointer
PDF
No ratings yet
Concept of Pointer
6 pages
Type Qualifiers in C: JB Enterprises Johan Bezem
PDF
No ratings yet
Type Qualifiers in C: JB Enterprises Johan Bezem
4 pages
Constant Pointers A Comprehensive Overview
PDF
No ratings yet
Constant Pointers A Comprehensive Overview
10 pages
3.const Qualifier
PDF
No ratings yet
3.const Qualifier
17 pages
C Programs (22-12-2020)
PDF
No ratings yet
C Programs (22-12-2020)
6 pages
Constants in C
PDF
No ratings yet
Constants in C
4 pages
10 Const
PDF
No ratings yet
10 Const
6 pages
Unit 4
PDF
No ratings yet
Unit 4
57 pages
C++ Notes Day-2
PDF
No ratings yet
C++ Notes Day-2
8 pages
CP+Spring2011+-+Lecture+5+ Pointers+ +strings
PDF
No ratings yet
CP+Spring2011+-+Lecture+5+ Pointers+ +strings
42 pages
W1 C3 Constants Inline FN
PDF
No ratings yet
W1 C3 Constants Inline FN
24 pages
Lecture 2 - Pointers
PDF
No ratings yet
Lecture 2 - Pointers
53 pages
Module 06 CV - Inline
PDF
No ratings yet
Module 06 CV - Inline
25 pages
CHTP5e - 07-Pointers 2
PDF
No ratings yet
CHTP5e - 07-Pointers 2
19 pages
7b Pointer Types
PDF
No ratings yet
7b Pointer Types
20 pages
PPS Unit 4 Notes Full
PDF
No ratings yet
PPS Unit 4 Notes Full
43 pages
Module 6
PDF
No ratings yet
Module 6
24 pages
5.3. Const
PDF
No ratings yet
5.3. Const
4 pages
Chapter 1 Pointers and DMA
PDF
No ratings yet
Chapter 1 Pointers and DMA
48 pages
C & C++ Language-3
PDF
100% (1)
C & C++ Language-3
99 pages
Pointers I
PDF
No ratings yet
Pointers I
33 pages
CP Unit-4 R19
PDF
No ratings yet
CP Unit-4 R19
22 pages
Constant Pointers: 'Int Const PTR Pointer To Constants: Const Int PTR
PDF
No ratings yet
Constant Pointers: 'Int Const PTR Pointer To Constants: Const Int PTR
1 page
OOP (CO1201) Unit-2 - Introduction To C++
PDF
No ratings yet
OOP (CO1201) Unit-2 - Introduction To C++
64 pages
Introduction To Programming: Lesson 5
PDF
No ratings yet
Introduction To Programming: Lesson 5
10 pages
Pointers and Structure
PDF
No ratings yet
Pointers and Structure
37 pages
10B MemoryManagement
PDF
No ratings yet
10B MemoryManagement
242 pages
Lec 20 Pointers in C
PDF
No ratings yet
Lec 20 Pointers in C
26 pages
Pointers Notes New
PDF
No ratings yet
Pointers Notes New
27 pages
Causes of Dangling Pointer in C PDF
PDF
No ratings yet
Causes of Dangling Pointer in C PDF
6 pages
Pointer C
PDF
No ratings yet
Pointer C
21 pages
Pointers 1
PDF
No ratings yet
Pointers 1
83 pages
Unit 5
PDF
No ratings yet
Unit 5
30 pages
Lec 9 Pointers
PDF
No ratings yet
Lec 9 Pointers
10 pages
Declaring Variable As Constant
PDF
No ratings yet
Declaring Variable As Constant
3 pages
Chapter 2 Pointers in C++
PDF
No ratings yet
Chapter 2 Pointers in C++
44 pages
Lec 20 Pointers in C
PDF
No ratings yet
Lec 20 Pointers in C
25 pages
Pointers
PDF
No ratings yet
Pointers
37 pages
PPSC Unit IV (18-1-23)
PDF
No ratings yet
PPSC Unit IV (18-1-23)
21 pages
Lecture 10 (Const Classes)
PDF
No ratings yet
Lecture 10 (Const Classes)
20 pages
Without This Message by Purchasing Novapdf : Print To PDF
PDF
No ratings yet
Without This Message by Purchasing Novapdf : Print To PDF
17 pages
ITC Lect 17 (Pointers and Strings - I)
PDF
No ratings yet
ITC Lect 17 (Pointers and Strings - I)
11 pages
Modifiers - Literals - Referencevariable - Typecasting - Constants and Manipulators in C++
PDF
No ratings yet
Modifiers - Literals - Referencevariable - Typecasting - Constants and Manipulators in C++
3 pages
C New Unit-5
PDF
No ratings yet
C New Unit-5
37 pages
Constants in C
PDF
No ratings yet
Constants in C
9 pages
C Programming Introduction
PDF
No ratings yet
C Programming Introduction
17 pages
C Progaramming
PDF
No ratings yet
C Progaramming
46 pages
Chapter by Gayatri
PDF
No ratings yet
Chapter by Gayatri
12 pages
Clockwise/Spiral Rule: See Also
PDF
No ratings yet
Clockwise/Spiral Rule: See Also
1 page
Unit - V Pointers, Structures & Unions, Files: M.Srinivasa Rao, Ass - Prof, CSE Department
PDF
No ratings yet
Unit - V Pointers, Structures & Unions, Files: M.Srinivasa Rao, Ass - Prof, CSE Department
24 pages
Constant
PDF
No ratings yet
Constant
2 pages
Zlib Alternatives
PDF
No ratings yet
Zlib Alternatives
25 pages
Extern Keyword
PDF
No ratings yet
Extern Keyword
5 pages
Masters Module Organisation
PDF
No ratings yet
Masters Module Organisation
1 page
Zlib Alternatives1
PDF
No ratings yet
Zlib Alternatives1
6 pages
Scanf Issue2
PDF
No ratings yet
Scanf Issue2
2 pages
Scanf Issue1
PDF
No ratings yet
Scanf Issue1
2 pages
Differences Between JDK, JRE and JVM
PDF
No ratings yet
Differences Between JDK, JRE and JVM
8 pages
How JVM Works - JVM Architecture
PDF
No ratings yet
How JVM Works - JVM Architecture
11 pages
Intro To Java
PDF
No ratings yet
Intro To Java
10 pages
Difference Between ++i and I++
PDF
No ratings yet
Difference Between ++i and I++
2 pages
Java Hello World Program
PDF
No ratings yet
Java Hello World Program
8 pages
The New Revised 20-Point Scale Grading System
PDF
No ratings yet
The New Revised 20-Point Scale Grading System
7 pages
Pattern Recognition and Machine Learning
PDF
No ratings yet
Pattern Recognition and Machine Learning
16 pages
Coronavirus PDF
PDF
No ratings yet
Coronavirus PDF
5 pages
Programme Specification: Mcomp Information Technology
PDF
No ratings yet
Programme Specification: Mcomp Information Technology
10 pages
Common Ways To Say Hello in Greece - GreekPod101
PDF
No ratings yet
Common Ways To Say Hello in Greece - GreekPod101
8 pages
FAQ Download Files PDF
PDF
No ratings yet
FAQ Download Files PDF
4 pages
Configuring Vlan 1 For Switch Management
PDF
No ratings yet
Configuring Vlan 1 For Switch Management
8 pages
What Type of A Leader Are You - Describe Your Leadership Style
PDF
No ratings yet
What Type of A Leader Are You - Describe Your Leadership Style
4 pages