You will often want to have a variable whose value can not be changed

You will often want to have a variable whose value can not be changed

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
You will often want to have a variable whose value can not be changed. For instance, it is generally considered stylistically poor to have constants without explanation, as in the following: float area = 3.1415 * radius * radius; Not only can the introduction of 3.1415 be confusing, but it is like that you will want to use the same value elsewhere in your program. It is better to assign the value to a constant variable using const : const PI = 3.1415; float area = PI * radius * radius; This syntax replaces C's #define syntax for defining constants. One advantage of this is that constant values have types in C++ and can therefore be checked at compile time. Sometimes you may want to forget entirely that your variables are being represented by numbers. In keeping track of
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: the days of the week, you might like to write something like: const int SUNDAY = 0; const int MONDAY = 1; const int TUESDAY = 2; etc. This will work, but C++ lets you more easily create your own enumerated type as follows: enum day_type {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; day_type favorite_day; favorite_day = Saturday; The enum command lets you define a new data type and the (constant) values a variable of this new data type can take on. It lets you do this all in one step and hides the fact that your values are being represented by numbers....
View Full Document

This note was uploaded on 12/12/2011 for the course CIS 101 taught by Professor Keefe during the Spring '08 term at Texas State.

Ask a homework question - tutors are online