data types, primitive types in c++, variables – declaration, initialization, scope telerik...
TRANSCRIPT
Data Types and Variables
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope
Telerik Software Academy
Telerik Software Academyacademy.telerik.com
Learning and Development
Table of Contents How computers work on data
Variables, example of using a variable in C++
What is a Data Type?
Identifiers in C++
Primitive Data Types in C++ and Using Them
Declaring Variables in C++ Variable Scope
Initializing Variables in C++ Default values
2
How Computers Work on Data
Variables, Using variables in C++, Identifiers
How Computing Works?
Computers are machines that process data Data is stored in the computer
memory in variables
Variables have name, data type and value
Example of variable definition and assignment in C++
4
int count = 5;Data type
Variable name
Variable value
What Is a Data Type? A data type:
Is a domain of values of similar characteristics
Defines the type of information stored in the computer memory (in a variable)
Examples:
Positive integers: 1, 2, 3, …
Alphabetical characters: a, b, c, …
Days of week: Monday, Tuesday, …5
Data Type Characteristics
A data type has: Name (C++ keyword) Size (how much memory is used) Default value
Example: Integer numbers in C++ Name: int Size: 32 bits (4 bytes) – on Windows* Default value: 0
* int is equal to the system “word”. E.g. x86 has 32-bit words. Windows always sets int to 32 bits 6
Primitive Data TypesRepresenting Integer, Floating-point
and Symbolic values
Integer Types Integer types:
Represent whole numbers
May be signed or unsigned
Have range of values, depending on the size of memory used
8
Name Description Size* Range*
charCharacter or small integer.
1byte signed: -128 to 127unsigned: 0 to 255
short int (short)
Short Integer. 2bytes signed: -32768 to 32767
unsigned: 0 to 65535
int Integer. 4bytessigned: -2147483648 to 2147483647unsigned: 0 to 4294967295
long int (long) Long integer. 4bytessigned: -2147483648 to 2147483647unsigned: 0 to 4294967295
Integer Types – Explained
int – the most common integer type
char – symbolic & integer type short int (or just short)
Smaller type than int
long int (or just long) Same as int on most systems
long long int (or just long long) Double the size of int on most
systems 9
Integer Types – Sizes C++ has no strict data type size on
any type Sizes determined by the system’s
data types
i.e. int may be 32, 64 or even 16 bits
C++ standards before C++11 only guarantee:
Generally, using int is the best option
sizeof(char) <=sizeof(short)sizeof(short) <=sizeof(int) sizeof(int) <=sizeof(long)sizeof(long) <=sizeof(long long)sizeof(char) == 1 //in bytes
10
Integer Types – Char C++ works with two char types
One for storing 8-bit numbers
One for storing characters
Writing simply char invokes the character type
If we need to store numbers Should write down "signed" or
"unsigned"
Tell the compiler we need char for numbers
Note: don’t store numbers in char, unless you have a very good reason
11
Using Integer and Symbol Types
Live Demo
Boolean Type – bool C++ has a Boolean type
bool – a value which is either true or false
Always takes up 1 byte 1 bit would be enough, but memory
is addressed per bytes, not per bit
Takes true, false, or numeric values Any non-zero numeric value is
interpreted as true
Zero is interpreted as false13
Using bool
Live Demo
Floating-Point Types Floating-Point numbers:
Represent real numbers (approximations) 2.3, 0.7, -Infinity, -1452342.2313,
etc.
Range of values, depending on memory used
Accuracy, depending on memory used
15
Name Description Size* Range*
float Floating point number. 4bytes ±1.5 × 10−45 to ±3.4 × 1038 (~7
digits)
doubleDouble precision floating point number.
8bytes ±5.0 × 10−324 to ±1.7 × 10308 (~15 digits)
long doubleLong double precision floating point number.
8bytes ±5.0 × 10−324 to ±1.7 × 10308 (~15 digits)
Floating-Point Types – Explained
float – fast, lower-precision double – slower, higher precision long double
High precision on some systems, not widely used
No guarantee on exact size (as with integers)
sizeof(float)<=sizeof(double)<=sizeof(long double)
16
Using Floating-Point Types
Live Demo
Declaring And Using Variables
Declaring Variables When declaring a variable we:
Specify its type
Specify its name (called identifier)
May give it an initial value
The syntax is the following:
Example:
19
<data_type> <identifier> [= <initialization>];
int height = 200;
Identifiers Variable names are called identifiers
All "words" in a language are identifiers Data types
Operators
Functions
Identifiers in C++ are case-sensitive THis != THIS != this
(the last being a reserved keyword)
20
Identifiers in C++ (1) C++ identifiers
One or more letters, digits or underscores
Start with a letter or underscore Avoid starting underscores & double
underscores
May be compiler-reserved
21
Identifiers in C++ (2) C++ identifiers
Can’t be a standard reserved keyword
Can’t be a name of operator representations
Can’t be a reserved compiler keyword Some compilers reserve their own
keywords
Bad C++ identifiers are detected compile-time Don’t need to remember all rules
Compiler will warn you about errors
22
Identifiers in C++ (3) Standard reserved identifiers in C++
Reserved identifiers for alternate operator representations (not always reserved)
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while
23
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Identifiers – Examples Examples of correct identifiers:
Examples of incorrect identifiers:
24
int new; // new is a keywordint 2Pac; // Cannot begin with a digit
int New = 2; // Here N is capitalint _2Pac; // This identifiers begins with _
string greeting = "Hello";
int n = 100; // Undescriptiveint numberOfClients = 100; // Descriptive
// Overdescriptive identifier:int numberOfPrivateClientOfTheFirm = 100;
Valid C++ IdentifiersLive Demo
Variable Scope Scope of a variable
Lines in code, where the identifier is valid
i.e. "where the variable is still alive"
Two kinds of scope in C++ Global (almost) – the variable is
visible and usable by all functions in the program
Local – the variable is visible and usable only in the current block i.e. in the inner-most { … }
26
Variable Scope Making a local variable – declare it in
a block
Making a global variable – declare outside any function or class
int main() {int a = 5; //local variablereturn 0;
}
27
#include <iostream>int a = 5; //global variableint main(){
a++;return 0;
}
Initializing VariablesWays to initialize, Default values
Initializing Variables C++ supports two ways of initializing
Through the assignment operator
Through calling the type constructor
Both ways are equivalent in the case of primitives
int a = 5;
29
int a (5);
Initializing Variables – Defaults
What happens to uninitialized variables?
C++ allows operating on uninitialized variables Actually variables get initialized
sometimes
Even if not initialized, variables get values
Whatever was in that part of memory
Where the variable is placed
int a; cout << a;
30
Initializing Variables – Defaults
Initialization depends on the variable scope
If the variable is global Initialized to default type value
E.g. for integers 0 If the variable is local
Undefined in standard
Usually garbage values from memory
Whatever values in memory marked free
31
Initializing VariablesLive Demo
форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно
програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop
уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
безплатен курс "Разработка на софтуер в cloud среда"
BG Coder - онлайн състезателна система - online judge
курсове и уроци по програмиране, книги – безплатно от Наков
безплатен курс "Качествен програмен код"
алго академия – състезателно програмиране, състезания
ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия
курс мобилни приложения с iPhone, Android, WP7, PhoneGap
free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно
?
? ? ??
?? ?
?
?
?
??
?
?
? ?
Questions?
?
Data Types and Variables
http://academy.telerik.com