In order to better communicate to our computers what exactly it is we want them to do, we've developed a wide range of programming languages to make the communication process easier.
- Compiled languages are translated to the target machine's native language by a program called a compiler. This can result in very fast code, especially if the compiler is effective at optimizing, however the resulting code may not port well across operating systems and the compilation process may take a while.
- Interpreted languages are read by a program called an interpreter and are executed by that program. While they are as portable as their interpreter and have no long compile times, interpreted languages are usually much slower than an equivalent compiled program.
- Just-In-Time compiled languages are quickly compiled when programs written in them need to be run (usually with very little optimization), offering a balance between performance and portability
-
A type system refers to the rules that the different types of variables of a language have to follow.
- Type Strength: Strong or Weak
Strong typing system puts restrictions on how different types of variables can be converted to each other without any converting statements.
A weak typing system would try to find some way to make the cast work.
- Type Expression: Manifest or Inferred
This deals with how the compiler/interpreter infers the types of variables.
Many languages require variables types to be explicitly defined, and thus rely on manifest typing.
Some however, will infer the type of the variable based on the contexts in which it is used, and thus use inferred typing.
- Type Checking: Static or Dynamic
If a language is statically typed, then the compiler/interpreter does the type checking once before the program runs/is compiled. If the language is dynamically type checked, then the types are checked at run-time.
- Type Safety: Safe or Unsafe
These refer to the degree to which a language will prohibit operations on typed variables that might lead to undefined behavior or errors. A safe language will do more to ensure that such operations or conversions do not occur, while an unsafe language will give more responsibility to the user in this regard.
- Most compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .cpp by default.
- Frequently used and available free is the GNU C/C++ Compiler.
- C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983.
- C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
- ISO-standardized.
For a time, and to this bloody day, C++ had no official standard and was maintained by a de-facto standard, however since 1998, C++ is standardized by a committee of the ISO. Their page may be accessed here.
- C is a compiled language.
C++ compiles directly to a machine's native code, allowing it to be one of the fastest languages in the world, if optimized.
- Strongly-typed Unsafe Language.
C++ is a language that expects the programmer to know what he or she is doing, but allows for incredible amounts of control as a result.
- ...supports both manifest and inferred typing.
As of the latest C++ standard, C++ supports both manifest and inferred typing, allowing flexibility and a means of avoiding verbosity where desired.
- ...supports both static and dynamic type checking.
C++ allows type conversions to be checked either at compile-time or at run-time, again offering another degree of flexibility. Most C++ type checking is, however, static.
- ...offers many paradigm choices.
C++ offers remarkable support for procedural, generic, and object-oriented programming paradigms, with many other paradigms being possible as well.
- ...is upwards compatible with C
C++, being a language that directly builds off C, is compatible with almost all C code. C++ can use C libraries with few to no modifications of the libraries' code.
These typing characteristics are not necessarily mutually exclusive, and some languages mix them
Paradigms
A programming paradigm is a methodology of programming.
-
Declarative
A declarative language will focus more on specifying what a language is supposed to accomplish rather than by what means it is supposed to accomplish it. Such a paradigm might be used to avoid undesired side-effects resulting from having to write one's own code.
- Functional
Functional programming is a subset of declarative programming that tries to express problems in terms of mathematical equations and functions. It goes out of its way to avoid the concepts of states and mutable variables which are common in imperative languages.
- Generic
Generic programming focuses on writing skeleton algorithms in terms of types that will be specified when the algorithm is actually used, thus allowing some leniency to programmers who wish to avoid strict strong typing rules. It can be a very powerful paradigm if well-implemented.
- Imperative
Imperative languages allow programmers to give the computer ordered lists of instructions without necessarily having to explicitly state the task. It can be thought of being the opposite of declarative programming.
- Structured
Structured programming languages aim to provide some form of noteworthy structure to a language, such as intuitive control over the order in which statements are executed (if X then do Y otherwise do Z, do X while Y is Z). Such languages generally deprecate "jumps", such as those provided by the goto statement in C and C++.
- Procedural
Although it is sometimes used as a synonym for imperative programming, a procedural programming language can also refer to an imperative structured programming language which supports the concept of procedures and subroutines (also known as functions in C or C++).
- Object-Oriented
Object-Oriented programming (sometimes abbreviated to OOP) is a subset of structured programming which expresses programs in the terms of "objects", which are meant to model objects in the real world. Such a paradigm allows code to be reused in remarkable ways and is meant to be easy to understand.
Comments:
//
One line comment.
/*
Multiline comment.
Multiline comment.
*/
int main() Function:
Must return an integer.
Must only be one "main" function.
Statements:
Statements can strech over multiple lines.
Statements must end with ;
Identifiers:
Can not use reserved keywords.
Identifier refers to name given to objects such as variables, functions, structures, etc.
May have letters (both uppercase and lowercase letters), digits and underscores.
The first 63 characters are checked for uniqueness.
Starting with _ is common for private identifiers.
Starting with __ is for system level private identifiers
Expression:
Anything that returns a value.
Assignment Expression: >li>Assigns a value to a variable.
Data type must be declared.
int x;
x = 69;
or:
int x = 69;
Refrence Variable:
Much like a pointer.
Can not define a Refrence without initalizing it.
C-String:
String is an array of characters strung together and terminated with a 0. Called a NULL terminated string.
char s[] = { "s", "t", "r", "i", "n", "g", 0 };
Same as:
char s[] = "string";
Use the string library. Known as an STL string:
#include <string >
string s1 = "Have a";
string s2 = " nice day";
To concatenate to strings use the plus sign:
string s3 = s1 + s2;
cout <<s3 <<endl;
Output:Have a nice day
Length of a String:
s3.length()
Check if String is empty or not:
s4.empty()
Convert string into constant character array:
const char* cstr = s3.c_str();
Compare two strings. This function will return 0, if the strings are equal; negative value, if string1 is less than string2 and positive value if string1 is greater than string2.
strcmp(string1, string2)
C-Array:
char s[] = { };
Fixed sized container for elements of a common data type. After declaring an array, we cannot change the size of the array. That means we can't reduce the size nor increase the size of an array.
Index uses integer value. x[0]; x[1];
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for( int i = 0; i <10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
Void:
Specifies that no value is available.
Built-in Types:
Type |
Keyword |
Boolean |
bool |
Character |
char |
Integer |
int |
Floating point |
float |
Double floating point |
double |
Valueless |
void |
Wide character |
wchar_t |
Integer Types
Type |
Storage size |
Value range |
char |
1 byte |
-128 to 127 or 0 to 255 |
unsigned char |
1 byte |
0 to 255 |
signed char |
1 byte |
-128 to 127 |
int |
2 or 4 bytes |
-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 |
unsigned int |
2 or 4 bytes |
0 to 65,535 or 0 to 4,294,967,295 |
short |
2 bytes |
-32,768 to 32,767 |
unsigned short |
2 bytes |
0 to 65,535 |
long |
4 bytes |
-2,147,483,648 to 2,147,483,647 |
unsigned long |
4 bytes |
0 to 4,294,967,295 |
Floating-Point Types
Type |
Storage size |
Value range |
Precision |
float |
4 byte |
1.2E-38 to 3.4E+38 |
6 decimal places |
double |
8 byte |
2.3E-308 to 1.7E+308 |
15 decimal places |
long double |
10 byte |
3.4E-4932 to 1.1E+4932 |
19 decimal places |
Modifier Types:
Signedness is a property of data types representing numbers in computer programs. A numeric variable is
signed
if it can represent both
positive and
negative numbers, and unsigned
if it can only
represent non-negative numbers
(zero or positive numbers).
A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations.
All four modifiers can be applied to the int type.
char type allows only signed and unsigned modifiers.
double type can be used with the long modifier
int type allows use of the shorthand notation. So, the following variable definitions are identical:
short int a;
and
short a;
unsigned int a;
and
unsigned a;
long int a;
and
long a;
(Signed ) int can have value -2,147,483,648 to 2,147,483,647. Unsigned int can have value 0 to 4,294,967,295.
sizeof(type):
Yields the storage size of the object or type in bytes.
printf("Storage size for int : %d \n", sizeof(int));
Constants/Literals:
Constants refer to fixed values that the program may not alter and they are called literals.
Known as a Read-only variable.
Constants can be of any of the basic data types and can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
Pointers:
Variable whose value is the address of another variable.
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var;// store address of var in pointer variable
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
// print the address stored in ip pointer variable
cout <<"Address stored in ip variable: " <<ip;
// access the value at the address available in pointer
cout <<"Value of *ip variable: ";
cout <<*ip <<endl
You can define arrays to hold a number of pointers.
There are four arithmetic operators that can be used on pointers: ++, --, +, -
C++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
C++ allows you to have pointer on a pointer and so on.
Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.
Loops:
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the for(;;) construct to signify an infinite loop.
while loop:
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
while( a <20 ) {
cout <<"value of a: " <<a <<endl;
a++;
};
do...while loop:
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
do {
cout <<"value of a: " <<a <<endl;
a = a + 1;
} while( a <20 );
for loop:
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
for (int i = 0; i <5; i++) {
cout <<"i is " <<i <<endl;
}
Control Statement |
Description |
break statement
|
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
|
continue statement
|
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
|
goto statement
|
Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.
|
Conditional Statements:
If Statement:
if (1 == 1) {
puts("True");
}
If-Else Statement:
if (1 == 1) {
puts("Equal");
} else if (1 <0) {
puts("Lesser Then");
} else {
puts("Greater Then");
}
Switch Statement:
Compares parameter to constants
// local variable declaration:
char grade = 'D';
switch (grade) {
case 'A' :
cout <<"Excellent!" <<endl;
break;
case 'B' :
case 'C' :
cout <<"Well done" <<endl;
break;
case 'D' :
cout <<"You passed" <<endl;
break;
case 'F' :
cout <<"Better try again" <<endl;
break;
default :
cout <<"Invalid grade" <<endl;
}
cout <<"Your grade is " <<grade <<endl;
Conditional Expressions:
conditional Expression ? expression1 : expression2;
** if the conditional Expression is true, expression1 executes, otherwise if the conditional Expression is false, expression 2 executes.
If both the true and false expressions assign values to the same variable, you can improve the efficiency by assigning the variable one time:
(a >b) ? (c = 25) : (c = 45);
Can be written as:
c = (a >b) ? 25 : 45;
The question mark helps the statement read as follows:
"Is a greater than b? If so, put 25 in c. Otherwise, put 45 in c."
if (a >b) {
c = 25;
} else {
c = 45;
}
Can be replaced with:
(a >b) ? (c = 25) : (c = 45);
Classes &Objects:
A class definition must be followed either by a semicolon or a list of declarations.
Access type specifies the possibility to access data members and member functions.
Public class members and functions can be used from outside of a class by any function or other classes. You can access public data members or function directly by using dot operator (.) or (arrow operator->with pointers).
Private class members and functions can be used inside its class. Protected members and functions cannot be accessed from other classes directly.
Protected access specifier allows friend functions and classes to access these data members and functions. Protected data members and functions can be used by the class derived from this class.
Preprocessor:
Give instruction to the compiler to preprocess the information before actual compilation starts.
Begin with #.
Only white-space characters may appear before a preprocessor directive on a line.
Preprocessor directives are not C++ statements, so they do not end in a semicolon (;).
#include is used to include a header file into the source file.
#define creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is:
#definemacro-name replacement-text
#define MIN(a, b) (((a) <(b)) ? a : b)
#define DEBUG
....
#ifdef DEBUG
cerr <<"Trace: Inside main function" <<endl;
#endif
#if
#else
#line
Predefined C++ Macros:
Macro |
Description |
__LINE__ |
This contain the current line number of the program when it is being compiled. |
__FILE__ |
This contain the current file name of the program when it is being compiled. |
__DATE__ |
This contains a string of the form month/day/year that is the date of the translation of the source file into object code. |
__TIME__ |
This contains a string of the form hour:minute:second that is the time at which the program was compiled. |
cout <<"Value of __LINE__ : " <<__LINE__ <<endl;
cout <<"Value of __FILE__ : " <<__FILE__ <<endl;
cout <<"Value of __DATE__ : " <<__DATE__ <<endl;
cout <<"Value of __TIME__ : " <<__TIME__ <<endl;
Function:
A Function is a block of code that may be called by and return a value to other code.
Function parameters can be an Assignment Expression
int x;
printf("%d", x = 32);
Call by value:
Function arguements are passed to functions by value. If you pass in a variable, a copy of the variable is passed to the function. Caller variable is unmodified.
Call by reference:
The # and ## Operators:
The # and ## preprocessor operators are available in C++ and ANSI/ISO C.
The # operator causes a replacement-text token to be converted to a string surrounded by quotes.
#include <iostream >
using namespace std;
#define MKSTR( x ) #x
int main () {
cout <<MKSTR(HELLO C++) <<endl;
return 0;
}
Output (No "" Around The String):
HELLO C++
Preprocessor turns the line:
cout <<MKSTR(HELLO C++) <<endl;
To:
cout <<"HELLO C++" <<endl;
The ## operator is used to concatenate two tokens.
cout requires lot of STL:
printf:
%c used for printing character object. Not a string. "x";
%d and %i converts a signed integer into decimal representation.
%f converts floating-point to the decimal notation.
%n returns the number of characters written so far by this call to the function.
%s writes a character string.
%x converts an unsigned integer into hexadecimal representation.
#include <cstdio >
#include <limits >
#include <cstdint >
#include <cinttypes >
using namespace std;
int main() {
printf("Strings:\n");
const char * s = "Hello";
printf("\t[%10s]\n\t[%-10s]\n\t[%*s]\n\t[%-10.*s]\n\t[%-*.*s]\n", s, s, 10, s, 4, s, 10, 4, s);
printf("Characters:\t%c %%\n", 65);
printf("Integers\n");
printf("Decimal:\t%i %d %.6i %i %.0i %+i %u\n", 1, 2, 3, 0, 0, 4, -1);
printf("Hexadecimal:\t%x %x %X %#x\n", 5, 10, 10, 6);
printf("Octal:\t%o %#o %#o\n", 10, 10, 4);
printf("Floating point\n");
printf("Rounding:\t%f %.0f %.32f\n", 1.5, 1.5, 1.3);
printf("Padding:\t%05.2f %.2f %5.2f\n", 1.5, 1.5, 1.5);
printf("Scientific:\t%E %e\n", 1.5, 1.5);
printf("Hexadecimal:\t%a %A\n", 1.5, 1.5);
printf("Special values:\t0/0=%g 1/0=%g\n", 0./0, 1./0);
printf("Variable width control:\n");
printf("right-justified variable width: '%*c'\n", 5, 'x');
int r =
printf("left-justified variable width : '%*c'\n", -5, 'x');
printf("(the last printf printed %d characters)\n", r);
//
fixed-width types
uint32_t val = numeric_limits <uint32_t >::max();
printf("Largest 32-bit value is %" PRIu32 " or %#" PRIx32 "\n", val, val);
return 0;
}
Output:
Strings:
[ Hello]
[Hello ]
[ Hello]
Characters: A %
Integers
Decimal: 1 2 000003 0 +4 4294967295
Hexadecimal: 5 a A 0x6
Octal: 12 012 04
Floating point Rounding: 1.500000 2 1.30000000000000004440892098500626
Padding: 01.50 1.50 1.50
Scientific: 1.500000E+000 1.500000e+000
Hexadecimal: 0x0p-63 0X0P-63
Special values: 0/0=nan 1/0=inf
Variable width control:
right-justified variable width: ' x'
left-justified variable width : 'x '
(the last printf printed 40 characters)
Largest 32-bit value is 4294967295 or 0xffffffff
windows.h:
- Windows-specific header file which contains declarations for all of the functions in the Windows API, all the common macros used by Windows programmers, and all the data types used by the various functions and subsystems.
- windows.h header file should be included before any other library. Even the C standard library. This is because the windows.h file includes macros and other components that may modify, extend, or replace things in these libraries.
- windows.h will cause all the string functions to use UNICODE.
- Many of the standard C library functions are already included in the Windows kernel without needing to load the standard libraries.
- Unlike the main() function, arguments of the WinMain() function are not optional.
- The first argument, hInstance, is a handle to the instance of the program you are writing.
- The second argument, hPrevInstance, is used if your program had any previous instance. If not, this argument can be ignored.
- The third argument, lpCmdLine, is a string that represents all items used on the command line to compile the application.
- The last argument, nCmdShow, controls how the window you are building will be displayed.
- This main window is created using a class object.
- The Win32 library provides two classes for creating the main window. They are WNDCLASS and WNDCLASSEX.
typedef struct _WNDCLASS {
UINT style;
WNDPROC lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HINSTANCE hInstance;
HICON hIcon;
HCURSOR hCursor;
HBRUSH hbrBackground;
LPCTSTR lpszMenuName;
LPCTSTR lpszClassName;
} WNDCLASS, *PW
|
typedef struct _WNDCLASSEX {
UINT cbSize;
UINT style;
WNDPROC lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HINSTANCE hInstance;
HICON hIcon;
HCURSOR hCursor;
HBRUSH hbrBackground;
LPCTSTR lpszMenuName;
LPCTSTR lpszClassName;
HICON hIconSm;
} WNDCLASSEX, *PWNDCLASSEX;
|
- When the window is on the screen, WinMain() dispatches messages to its message-handling function.
- How does the compiler know to invoke wWinMain instead of the standard main function? What actually happens is that the Microsoft C runtime library (CRT) provides an implementation of main that calls either WinMain or wWinMain.
- Everything in Windows is a window. That includes buttons, menus, menu items, sliders, and, of course, windows.
- Nearly everything in Windows can send or receive messages.
Restriction!
Pointers may not be passed BYREF, so the lpszCmdLine parameter of WINMAIN must be declared to be passed BYVAL.
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
MessageBox(NULL, "Goodbye, cruel world!", "Note", MB_OK);
return 0;
}
#include <windows.h>
int main() {
MessageBox(0, "Press OK", "Hi", MB_SETFOREGROUND);
return 0;
}
Child header files:
- excpt.h – Exception handling
- stdarg.h – Variable-argument functions (standard C header)
- windef.h – Macros and types
- winnt.h – Macros and types (for Windows NT)
- basetsd.h – More vrious types
- guiddef.h – the GUID type
- ctype.h – character classification (standard C header)
- string.h – strings and buffers (standard C header)
- winbase.h – kernel32.dll, advapi32.dll
- winerror.h – Windows error codes
- wingdi.h – Graphics Device Interface
- winuser.h – user32.dll: user services
- winnls.h – NLS (Native Language Support)
- wincon.h – console services
- winver.h – version information
- winreg.h – Windows registry
- winnetwk.h – WNet (Windows Networking)
- winsvc.h – Windows services and the SCM (Service Control Manager)
- imm.h – Input Method Editor