2E. Values and Types

A starting point for any programming language is data: what are the data values that a program can work with?

C++ is a typed language. Every value has a type, and the compiler checks that programs are sensible from the standpoint of types.

Fundamental C++ types

int

Values of type int are integers from −2,147,483,648 to 2,147,483,647. Constants of type int (which you can write in C++ programs) include 45 and -30. You cannot write a comma in a number in C++.

long

Values of type long are integers from −18,446,744,073,709,551,616 to 18,446,744,073,709,551,615. Constants of type long include 45L and -30L.

double

Values of type double are real numbers stored to about 15 decimal digits of precision. Constants of type double include 29.05. In cases where real numbers are very large or very small, you can write constants such as 71.0E25 (71.0×1025) and 1.0E-25 (1.0×10−25).

bool

There are two values of type bool: true and false. They are used as answers of yes/no questions.

char

Values of type char are characters in the ASCII alphabet. A character constant is written in single-quote marks, as in 'a', 'x', and '('. Character constant ' ' is the space character, '\n' indicates an end-of-line marker and '\t' is a tab character.

const char*

A string is a sequence of zero or more characters. Write a string constant in double-quotes, as in "I am a string". A string has type const char*.

String constant "" indicates an empty string, a string with no characters in it. String constant "first\tsecond\n" has length 13; \t and \n are just one character each.

C++ has an unusual feature for writing string constants. If you write two string constants in a row, they are glued together into one string. For example, "abc" "def" has the same meaning as "abcdef". Don't over-generalize this. It only works for two consecutive string constants.