Saturday 20 April 2013

constant in c

  • The keyword const(constant) can be used to freeze the value of an object. 
  • const objects will be initialized (as their value cannot otherwise be set!). 
  • const can also be used as a type qualifier on function parameters to prevent accidental modification of the parameter within the function.


void fred(const int x);
int main()
{
const int i = 15;
int j = 16;
i = 5; // illegal
fred(j);
return 0;
}
void fred(const int x)
{
x = 6; // illegal
}

When applying const to a pointer we can indicate that the pointer should be unmodified,
or that the data pointed to should remain constant. The alternatives are given below:

const char *ptr1 = "Hi"; // data pointed to is const
char *const ptr2 = "Hi"; // pointer is constant
const char *const ptr3 = "Hi"; // both pointer and data
// are constants
const objects can be used in array declarations, they cannot in C. The following is legal C++, but illegal C:
const int size = 10;
float vals[size];

No comments:

Post a Comment