DataType variableName ; |
int a ; a is an int int[] b ; b is an int[] (array of int) |
|
int a ; // meaning: the expression a is of the type int |
int *a ; should be read as: int *a ; // meaning: the expression *a is an int |
$64,000 question:
|
Explanation:
|
|
int *a, b ; |
This variable definition defines:
*a is an int ===> a is a reference variable to an int b is an int ===> b is an int |
int *a, *b ; |
This variable definition defines:
*a is an int ===> a is a reference variable to an int *b is an int ===> b is also a reference variable an int |
int a ; read as: a is an int int const a ; read as: const a is an int <==> a is an int and you cannot update a |
int const *a ; |
Answer:
int const *a means: const *a is an int <==> *a is an int and you cannot update *a <==> a is a reference to an int and you cannot update *a |
|
Example:
int main(int argc, char *argv[]) { int a; const int *p; // You CANNOT use *p to update the int value ! a = 4; p = &a; *p = 100; // Illegal !!! } |
Result:
UNIX>> gcc const1.c const1.c: In function 'main': const1.c:15: error: assignment of read-only location '*p' |
How to run the program:
|
int * const a ; |
Answer:
int * const a means: * const a is an int <==> const a is a reference variable to an int <==> a is a reference variable to an int and you cannot update a |
|
Example:
int main(int argc, char *argv[]) { int a = 4; int b = 7; int * const p = &a; // p points to a, and you cannot update p printf ("a = %d, b = %d\n", a, b); *p = 555; // You CAN update *p (it is not the same as p) printf ("a = %d, b = %d\n", a, b); p = &b; // Illegal - can't update p /* -------------------------- Contrast with this: -------------------------- */ int const * q = &a; // *q is a const q = &b; // You CAN update q *q = 555; // Illegal: You CANNOT update *q } |
Result:
UNIX>> gcc const2.c const2.c: In function 'main': const2.c:line 20: error: assignment of read-only variable 'p' const2.c:line 31: error: assignment of read-only location '*q' |
How to run the program:
|
Exercise:
|