C++ Primer For Java Programmers Variables And Data Types<< The Main Function | Table of Contents | Function Declarations >>
As in all programming languages, we use identifiers to name things such as variables, functions, data types, classes, etc. Identifiers in C++:
VariablesVariables in C++ must be explicitly declared as they are in Java. (:source lang=cpp:)int grade, sum, total; double average, salary; In C++, variables are not initialized when they are created. You can declare a variable and initialize it at the same time (:source lang=cpp:)int total = 0; double taxRate = 0.05; Data TypesC++ provides a number of primitive data types including
Literal values can be used in C++ programs just like in any other language. In C++, literals for the basic types are specified as follows
AssignmentsAssignments in C++ use the the single equal sign ( grade = 89; taxRate = 0.155; Attempting to sign incompatable types will result in a compilation error. Constant DeclarationsConstant variables or named literals are defined using the keyword const float PI = 3.1415926; const int NUM_VALUES = 4; Once a value has been assigned to a constant variable, it can not be changed. Constant variables are typically named in all uppercase to distinguish them from other variables. Mathematical OperatorsMathematical expressions are constructed using the mathematical operators (:source lang=cpp:)avg = (grade1 + grade2 + grade3) / 3.0; which are the same as those in Java + - * / % ( ) If both operands are integers, then integer arithmetic is performed and the result will be an integer value. If one or both of the operands are real values, then real arithmetic is performed and the result is a real value. (For operator precedence, see the order of precedence table.) Type CastingThere are two approaches for typecasting in C++: the C method or the new C++ method. In C, a value can be typecast or forced to a new type by specifying the value within parentheses (:source lang=cpp:)int count = 3; double avg; : avg = (grade1 + grade2 + grade3) / (float) count while in C++ the type to which a value is being typecast is used as method (:source lang=cpp:)avg = (grade1 + grade2 + grade3) / float( count ) Type DefinitionsIn addition to the primitive data types, users can create their own types by simply renaming existing types or constructing new types from existing ones usin the typedef unsigned char byte; we create a new type called byte value; byte small = 4; The general form of the typedef original-type new-name;
|