C++
Integer Literal
Can be a decimal, octal, or hexadecimal constant Prefix specifies the "base" or "radix": - 0x for hexadecimal - 0 for octal - nothing for decimal Suffix: - U for unsigned - L for long
Example of a function using global + local variables
#include <iostream> using namespace std; // Global variable declaration: int g; int main () { // Local variable Declaration: int a, b; // Local variable Initialization: a = 10; b = 20; g = a + b; cout << g; return 0; }
lvalue
- Expressions that can refer to a memory location - Either the left-hand or right-hand side of an assignment - Variables are lvalues
"type modifiers" for basic types
-signed -unsigned -short -long
Storage classes in C++
1. Auto 2. Register 3. Static 4. Extern 5. Mutable
Examples of Legal vs Illegal integer variables
212 // Legal 215u // Legal 0xFeeL // Legal 078 // Illegal: 8 is not an octal digit 032UU // Illegal: cannot repeat a suffix
Examples of various types of Integer literals
85 // Decimal 0213 // Octal 0x4b // Hexadecimal 30 // Int 30u // Unsigned Int 30l // Long 30ul // Unsigned Long
example of const vs volatile vs restrict
?????
Whitespace in C++
A blank line, tab, newline character, and comments will all be ignored by C++ compiler However, spaces are important for identifying where one element ends and another begins... int age; Other times spaces are just there for readability
wchar_t - what is it?
A wide character type
What is an unsigned long?
Assuming 4 bytes, - A long has the range of -2,147,483,648 to 2,147,483,647 . -An unsigned long has the range of 0 to 4,294,967,295 . - Overflow: For a signed type, an overflow has unspecified behavior. But for an unsigned type, overflow is guaranteed to "wrap around."
Primitive Built-in Types (& keyword)
Boolean (bool) Character (char) Integer (int) Floating point (float) Double floating point (double) Valueless (void) Wide character (wchar_t)
What is the default numbering for an enumeration? How can you change the value?
By default, the value of the first name is 0, then 1, then 2: enum colors { red, green, blue} c; To give a name a specific value, use an initializer: enum colors { red, green=5, blue} c; Here, blue will have a value of 6!
What's a "middle-level" language?
Comprises a combination of both high-level and low-level language features
Global Variable
Defined outside all the functions, usually at the top Will hold their value throughout the lifetime of the program Can be accessed by any function
What is a C++ program? (Basic Syntax)
Definition: A collectoin of objects that communicate via invoking each others' methods
Character literals
Enclosed in single quotes 'x' is a simple variable of char type L'x' represents a wide character literal and should be stored in wchar_t type of variable
Various other types of variables (to be covered later)
Enumeration Pointer Array Reference Data Structures Classes
What are Constants aka. Literals?
Fixed values that the program MAY NOT ALTER They can be any of the basic data types: - Integer Numerals - Floating-Point Numerals - Characters - Strings - Boolean Values
What is the ANSI standard?
Makes sure that C++ is portable (that is, you can use it on Windows, Mac, Unix, or anything with no errors)
Does C++ recognize the end of a line as a terminator?
No
const What does this type modifier do?
Objects of type const cannot be changed by your program during execution
'int main()'
On this line, this is the main function where program execution begins
What's a char data type?
One byte, single octet This is an integer type
auto storage class
The default storage class for all local variables
volatile What does this type modifier do?
The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program.
What is C++ generally used for?
To write device drivers & other software that rely on direct manipulation of hardware under realtime constraints Or, for teaching & research Also, for Mac & Windows - the primary user interfaces of these systems are written in C++
signed & unsigned (modifiers)
Used to modify int or char data types Can also be used as a prefix to long or short modifiers
<< operator
Used to pass multiple values out to the screen
What's a Method?
a behavior A class can contain many methods This is where LOGICS are written, data is manipulated, and all the actions are executed.
double - what is it?
a double-precision floating point value
sizeof()
an operator that gets teh size of vaarious data types
C++ reserved words...
asm else new this auto enum operator throw bool explicit private true break export protected try case extern public typedef catch false register typeid char float reinterpret_cast typename class for return union const friend short unsigned const_cast goto signed using continue if sizeof virtual default inline static void delete int static_cast volatile do long struct wchar_t double mutable switch while dynamic_cast namespace template
What are the initializer values for an automatically initialized global variable?
for int, float, or double, initializer is 0. for char, initializer is '\0' for pointer, initializer is NULL.
/* this is a comment */ // this is a comment
format for comments You can also nest them
enum
keyword that creates an enumeration type syntax: enum enum-name { list of names } var-list; ('enum-name' is the enumeration's type name; the list of names is separated by commas)
void - what is it?
represents the absence of type
What are variables?
reserved memory locations to store values When you create a value, you reserve some space in memory.
Boolean literals
true = 1 false = 0
What's a bool data type?
Stores either True or False
typedef
a way to create a new name for an existing type Syntax: typedef type newname; Ex. typedef int feet; Tells the compiler that "feet" is another name for "int"
What does a variable do?
provides us with named storage that our programs can manipulate
Whitespace and string literals : Example of equivalent things
"hello, dear" "hello, \ dear" "hello, " "d" "dear" ** Note that whitespace is not affecting them
In a C++ program, what's a header?
# include <iostream> Headers contain information that's necessary for the program
rvalue
- Refers to a data value that is stored at some address in memory - Cannot have a value assigned to it - May only appear on the right hand side (not the left hand side) of an assignment - Numeric literals are rvalues ex. valid: int g = 20; ex invalid: 10 = 20;
Words that describe C++
- Statically typed - Compiled - General purpose - Case sensistive - Free-form - Supports procedural, object-oriented, and generic programming -"middle-level" language
What's a namespace?
..
Still don't understnad what the diff is between signed and unsigned int
...
What's a compiled language??
...
What's a free-form language?
...
What are the three standard libraries in C++?
1. Core Language: including building blocks such as variables, data types, and literals 2. C++ Standard Library: includes a rich set of functions for manipulating files, strings, etc. 3. The Standard Template Library (STL): includes a rich set of methods for manipulating data structures, etc.
What are the four pillars of OOP?
1. Encapsulation 2. Data Hiding 3. Inheritance 4. Polymorphism All these features are suppored in C++.
C++ Modifier Types
A modifier is used to alter the meaning of the base type (int, char, or double data types) The data type modifiers are: - signed or unsigned (for int, char) - long (for int or double) - short (for int)
What is a C++ Identifier?
A name used to identify a variable, function, class, module, or other user-defined term Don't use @, $, % for identifiers but A,a,123,or _ are ok (case sensitive)
restrict What does this type modifier do?
A pointer qualified by restrict is initially the only means by which the object it points to can be accessed
What is a block?
A set of logically connected statements that are surrounded by {} brackets
float - what is it?
A single-precision floating point value
What's an Object?
An object is an instance of a class. Objects have STATES and BEHAVIORS
What if the program has the same name for local and global variables?
That's ok, but the value of the LOCAL variable will take precedence over the global. ex. // Global variable declaration: int g = 20; int main () { // Local variable Declaration: int g = 10; cout << g; return 0; } Returns 10 and not 20.
What is the type of the enumerator?
The enumeration Each enumerator is a constant whose type is the enumeration
Example where variables are declared at the top, but are defined inside the main function:
# include <iostream> using namespace std; // Variable declaration: extern int a, b; extern int c; extern float f; int main() { // Variable definition: int a, b; int c; float f; // Actual initializeation a = 10; b = 20; c = a + b; cout << c << endl; f = 70.0 / 30.0 cout << f << endl; return 0; } OUTPUT after compilation: 30 23.333
Example C++ program
# include <iostream> using namespace std; int main() { cout << "Hello World"; return 0; }
Floating-Point Literals have what parts?
An integer part, a decimal point, a fractional part, and an exponent part Either written in decimal form for exponent form Ex. 3.14159 // Legal 314159E-5L // Legal 510E // Illegal: incomplete exponent 210f // Illegal: no decimal or exponent .e55 // Illegal: missing integer or fraction
What's an enumerated type?
Declares an optional type name plus identifier(s) that can be used as values of the type.
char < short < int < long < long long What are the sizes respectively?
Order of sizes: char >= 8 bits short >= 16 bits long >= 32 bits long long >= 64 bits
What does a variable definition do?
Tells the compiler where and how much storage to create for the variable Specifies a data type, contains a list of one or more variables of that type. Syntax: type variable_list; Where type is a valid data type (char, int, float, double, bool, or user-defined object) and variable_list conatins identifier names, separated by commas. Valid declaration examples: int i, j, k; char c, ch; float f, salary; double d;
const
Use this prefix to declare constants with a specific type: const type variable = value; Ex #include <iostream> using namespace std; int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; } RETURNS: 50 Note: Define constants in ALL CAPITALS
extern
a keyword that declares a variable at a place It can only be defined once in a file, function, or block of code.
Once you have created a new name "feet" for type "int" using typedef, typedef int feet; How do you create an integer variable called "distance" that uses the new name?
feet distance; This is a declaration that creates an integer variable with the new name
endl
inserts a new-line character after every line and << operator being used to pass multiple values out to the screen
Global variables are initialized automatically by the system as long as you define them as what data types?
int char float double pointer
What if you define a function name at the time of declaration, then give the actual definition somewhere else?
# include <iostream> using namespace std; // function declaration int func(); int main () { // function call int i = func(); } // function definition int func() { return 0; }
Example of local variable declaration & initializatoin
# include <iostream> using namespace std; // function declaration int main () { // Local variable Declaration: int a, b; int c; // Local variable Initialization: a = 10; b = 20; c = a + b; cout << c; return 0; }
code for showing the size of various data types
#include <iostream> using namespace std; int main() { cout << "Size of char : " << sizeof(char) << endl; cout << "Size of int : " << sizeof(int) << endl; cout << "Size of short int : " << sizeof(short int) << endl; cout << "Size of long int : " << sizeof(long int) << endl; cout << "Size of float : " << sizeof(float) << endl; cout << "Size of double : " << sizeof(double) << endl; cout << "Size of wchar_t : " << sizeof(wchar_t) << endl; return 0; } OUTPUT Size of char : 1 Size of int : 4 Size of short int : 2 Size of long int : 4 Size of float : 4 Size of double : 8 Size of wchar_t : 4
What are the three places where variables can be declared?
1. Local Variable: inside a function or block 2. Formal Paramters: in the definition of a function parameters 3. Global Variables: outside of all functions
What are the four types of variables in C++?
1. Object variables 2. Class variables 3. Methods variables 4. Instance variables
Two ways of defining constants:
1. Use #define preprocessor 2. Use const keyword
Three Type Qualifiers in C++
1. const 2. volatile 3. restrict
int - what is it?
the most natural size of integer for the machine
Instance Variables
Each object has a unique set of instance variables. An object's state is created by the values assigned to these instance variables.
Escape Sequences (codes preceded by backslash w/ special meaning)
Escape sequence, Meaning \\ \ character \' ' character \" " character \? ? character \a Alert or bell \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \ooo Octal number of one to three digits \xhh . . . Hexadecimal number of one or more digits
How do you initialize variables as part of the declaration?
If you want to assign an initial value, use an equals sign. SYntax: type variable_name = value; Examples: extern int d = 3, f=5; // declaration of d and f int d=3, f=5 // declaration and init of d and f byte z = 22; //definition and initialier of z char x = 'x'; // the variable x has the value 'x'
cout and cint
In C++, the standard output and input streams
semicolon;
In C++, this is the statement terminator indicates the end of one logical entity
What does it mean to be "statically typed"?
In a programming language, when type checking is performed during compile-time as opposed to run-time
How do you run a .cpp program on Terminal?
Open a text editor and add the code as above. Save the file as: hello.cpp Open a command prompt and go to the directory where you saved the file. Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file. Now, type 'a.out' to run your program. You will be able to see ' Hello World ' printed on the window. $ g++ hello.cpp $ ./a.out Hello World Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp. https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm
What does variable declaration do for the compiler?
Provides assurance that there is one variable existing with the given type and name so that the compiler can proceed for further compilation without needing complete detail about the variable
How to use #define preprocessor
Syntax: #define identifier value Ex. # include <iostream> using namespace std; #define LENGTH 10 #define WIDTH 5 #define NEWLINE '\n' int main() { int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; } OUTPUT: 50
'using namespace std;' ^^ What does this do?
Tells the compiler to use the std namespace.
What is a long?
The C++ compiler treats variables of type char , signed char , and unsigned char as having different types. ... Signed short is a synonym for short . int. Type int is an integral type that is larger than or equal to the size of type short int , and shorter than or equal to the size of type long .
'cout << "This is program";'
This line causes the message to be displayed on the screen.
'return 0;'
This line terminates the main() function and causes it to return the value 0 to the calling process.
local variables
Variables that are declared inside a function or block Can only be used by statements that are inside that function or block Cannot be used by outside functions
What is the default if you don't have an initializer?
Variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0) or undefined.
'// main() is where program execution begins.'
a single-line comment //
What's a Class?
a template / blueprint that describes the behaviors/states that object of its type support
Variables have a specific type. What does this mean?
determines - size & layout of the variable's memory - range of values that can be stored in that memory - the set of operations that can be applied to the variable
String Literals
enclosed in double quotes A string can contain characters that are similar to character literals: - plain characters - escape seuqences - universal characters
How do you create an enumeration of colors called "colors" and a variable "c" of type color? Then, assign c to the value "blue"?
enum colors { red, green, blue } c; c = blue;
How would you use escape sequence characters to write Hello World
int main() { cout << "Hello\tWorld\n\n"; return 0; } (\t is horizontal tab; \n is newline)
What is the difference between how C++ interprets signed and unsigned integer modifiers?
int main() { short int i; // a signed short integer short unsigned int j; // an unsigned short integer j = 50000; i = j; cout << i << " " << j; return 0; } RETURNS: -15536 50000 /*Why? The bit pattern that represents 50000 as a short, unsigned integer is interpreted as -15,536 by a short */
The two kinds of expressions in C++
lvalues and rvalues
You don't have to say "int" if you don't want to, it will be automatically inferred:
unsigned x; unsigned int y; short x; short int z; long x; long int z; (All ok for shorthand)