User Tools

Site Tools


cplusplus:pointers_2

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
cplusplus:pointers_2 [2016/03/05 22:35] – [Constant pointer to constant data] mithatcplusplus:pointers_2 [2016/03/05 22:38] mithat
Line 99: Line 99:
 ===== The const qualifier and pointers ===== ===== The const qualifier and pointers =====
  
-You are already familiar with C++'s ''const'' qualifier when used with regular variables. In brief:+You are already familiar with C++'s ''const'' qualifier when used with regular variables. To review:
  
   * ''const'' variables cannot be changed (i.e., they become //constants//).   * ''const'' variables cannot be changed (i.e., they become //constants//).
Line 140: Line 140:
 You can also create a pointer that is itself not constant (i.e., it can be reassigned or can change "what is being pointed to") but that cannot change the value of "what is being pointed to." This is a **pointer to constant data** or simply **pointer to constant**. You can also create a pointer that is itself not constant (i.e., it can be reassigned or can change "what is being pointed to") but that cannot change the value of "what is being pointed to." This is a **pointer to constant data** or simply **pointer to constant**.
  
-To create a pointer to constant, use the ''const'' keyword to qualify the type being pointed to.+To create a pointer to constant data, use the ''const'' keyword to qualify the type being pointed to.
  
 <code cpp> <code cpp>
Line 149: Line 149:
 myPtr = &y;    // no problem, myPtr now points to y myPtr = &y;    // no problem, myPtr now points to y
 </code> </code>
 +
 +
 +<WRAP center round tip 90%>
 +One way to remember this is "const modifies the thing immediately following it." In the case of:
 +<code c++>int *const myPtr = &x;</code>
 +''const'' modifies ''myPtr'', meaning the value of ''myPtr'' is constant. In the case of:
 +<code c++>const int *myPtr = &x;</code>
 +''const'' modifies ''int'', meaning the value of the ''int'' is constant.
 +</WRAP>
  
 ==== Constant pointer to constant data ==== ==== Constant pointer to constant data ====
Line 161: Line 170:
 myPtr = &y;    // syntax error! myPtr = &y;    // syntax error!
 </code> </code>
- 
-<WRAP center round tip 90%> 
-One way to remember this is "const modifies the thing immediately following it." In the case of <code c++>int *const myPtr = &x;</code> ''const'' modifies ''myPtr'', meaning the value of ''myPtr'' is constant. In the case of <code c++>const int *myPtr = &x;</code> ''const'' modifies ''int'', meaning the value of the ''int'' is constant. 
-</WRAP> 
  
cplusplus/pointers_2.txt · Last modified: 2019/03/28 16:55 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki