This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Arrays and Pointers 1 Arrays and Pointers In this part we investigate the relationship between pointers and arrays. Using const in pointer declarations Consider the following declaration. int a = 10; // int variable a is modifiable const int b = 20; // int variable b is not modifiable Variable a can be modified by a statement, such as a = 25; . The value of b cannot be modified any where in the program, since b is declared as a const variable. Note that any const variable has to be initialized at the time of its declaration. For example, look at the following code segment. int a; a = 10; // this is OK const int b; // illegal - will not compile b = 20; // will not compile Since b is a const , we must initialize b with a value during its declaration. Placing const in a pointer declaration In a pointer declaration, const can be used in two different places, with two different meanings. Consider the following code segment. int a = 10, b = 20; const int *pc; // const placed at the beginning pc = &a; int *const cp = &b; //const placed before pointer name Arrays and Pointers 2 The two integer variables and the pointers pointing to them is depicted below. It helps to read the pointer declarations backwards. The declaration const int *pc; tells the compiler that pc is a pointer to an interger constant . Here the const qualifier is for the target variable, but not for the pointer. What does this mean? When the pointer pc is pointing to a target variable, such as a , we cannot modify the target variable using pc . That is, a statement such as *pc = 44; // this will not compile will not compile, because *pc , the target variable, behaves like a const (unmodifiable) variable. Note that the following statement compiles because a is not a const variable....
View Full Document
- Fall '08