C++ Intro

where learning C/C++ ?

http://www.tutorialspoint.com/cplusplus   +++++

http://www.learncpp.com/

http://www.cplusplus.com

http://www.cprogramming.com

http://cpp.developpez.com/cours/cpp/    (French)    books, white papers,…

http://www.siteduzero.com/informatique/tutoriels/programmez-avec-le-langage-c   (French)

www.youtube.com,  search for “Buckys C++ Programming Tutorials”, offers 73 videos

 


Coding Standards

– Coding standards are a great place to start :  http://www.ganssle.com/fsm.htm

– Documenting you code so you can follow what you did if you come back to it years later.

– Not use native types as these can be both platform and compiler dependent.

– KISS principle, is an acronym for “Keep it simple, stupid”.

– Use a template, something like shown below :

// =============================================================
//
// MyFirstCProgram.C Date/Version: 2014.06.25
// Purpose: Displays text to an output device
//
// Funtion Name: Print_Str

// Input(s) *char String to be displayed
// Output: void
//
// Compiler or IDE version: Keil uVision ver. xxxx.xx
// Microprocesor: Microchip 16F877A @ 12.8 MHz
// Developer: Jose Goncalves
//
// =============================================================

–  don´t forget to return () a value … allow to know if a program/function ended succesfully.

– Each module should be small enough to be viewed on a single screen (without scrolling up or down) and on single printed page.

– One hour of design work can often save 10s of hours of coding and debugging.

 


Introduction ————————————————-

Programs

There are two types of programs, console, and GUI (Graphical User Interface) that corresponds to the windows that we know.To create GUI programs we need special libraries like Qt. Qt it´s not only a library, actually it´s more than that, it is a framework,i.e, it contains a GUI modul, a network module, a SQL modul, etc...
Qt is multi-platform, or cross-platform; may run in Wndows, Linux, Mac OS X,...

Cross-platform software may be divided into two types; one requires individual building or compilation for each platform that it supports, and the other one can be directly run on any platform without special preparation, e.g., software written in an interpreted language or pre-compiled portable bytecode for which the interpreters or run-time packages are common or standard components of all platforms.

IDE


An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of a source code editor, build automation tools and a debugger.

 

C/C++ IDE : Eclipse , DevC++ , CodeBlocks, Microsoft Visual Studio, Qt, etc…

The GNU Compiler Collection (GCC)

The GNU Compiler Collection (GCC) is a compiler system produced by the GNU Project supporting various programming languages.


MinGW (Minimalist GNU for Windows)
http://www.mingw.org/

 


Basics of C++   ------------------------------------------------

#include <iostream>
using namespace std;
 
int main()
{
  cout<<"HEY, you, I'm alive! Oh, and Hello World!\n";
  cin.get();   //This will cause the program to wait for you to press a key before exiting
 // may be also used  system ("PAUSE") ;  
}

 

The iostream header file comes with your compiler andallows you to perform input and output. Using #include effectively takes everything in the header file and pastes it into your program. By including header files, you gain access to the many functionsprovided by your compiler.

cin

string user_first_name;
cin >> user_last_name;

Comments :

// this is one line comment

/* this is multi-lines

    comment */ 

You may add white space anywhere you like in your program to enhance readability, exept in the middle of a word.

In C++, all language keywords, all functions and all variables arecase sensitive.

You have to tell what size you need before you can use a C++ variable :

int

unsigned
Float
Double
char ...  

int x = 0;
cout << x++;
   // The output is 0. ++ being executed after getting thevalue of the variable.

int x = 0;
cout << ++x;
  // The out put is 1. first adds 1 to x, and then gets the value of x.

n1 = 5 ;

n2 = ++n1 ;     // n1 and n2 is 6

n2 = n1++ ;     // n1 is 6, n2 is 5

x++ ;       // add 1 to x

x+ = 5 ;  // add 5 to x

x * = 5;   // multiply 5 to x

Namespace

namespace abc {
 int bar;
}
 

Within this block, identifiers can be used exactly as they are declared. Outside of this block, the namespace specifier must be prefixed. For example, outside ofnamespace abc,bar must be written abc::bar to be accessed. 

C++ includes another construct that makes this verbosity unnecessary. By adding the line  using namespace abc;  to a piece of code, the prefix abc:: is no longer needed.

Namespaces in C++ are most often used to avoid naming collisions. Although namespaces are used extensively in recent C++ code, most older code does not use this facility. For example, the entire C++ standard library is defined within namespace std, but before standardization many components were originally in the global namespace.



C++ standard library & namespace

 

std::string name;


<=>


using namespace std;

string name;


std::cout << …

Standard Template Library

http://en.wikipedia.org/wiki/Standard_Template_Library 

The Standard Template Library (STL) is a c++ library that influenced many parts of the C++ standard library. It provides four components called algorythms, containers, functional, and iterators.

In computer science, a container is a class, a data structure or an abstract data type (ADT) whose instances are collections of other objects. In other words; they are used for storing objects in an organized way following specific access rules. The size of the container depends on the number of the objects (elements) it contains.The underlying implementation of various types of containers may vary in space and time complexity allowing for flexibility in choosing the right implementation for a given scenario.


Functions -------------------------------------------------------

First thing to write is the return type of the function, int, void, char,....
If a function does not return a value - for example, a function that just prints something to the screen - you can declare its return type as void. Example : void printScreen()

int add (int x, int y)   // this function takes two arguments, x and y. will return an int value.
{
return x + y;
}

 

Computer programs works from the top to down, so before using a function, we have to tell C++ that is a function. there is two ways to do that, creating the function before using it, or the second method is called "function prototyping".

#include <iostream>
using namespace std;

int add (int x, int y)
{
return x + y;
}

int main ()
{
int result = add( 1, 2 ); // call add and assign the result to a variable
cout << “The result is: ” << result << ‘\n’;
cout << “Adding 3 and 4 gives us: ” << add( 3, 4 );
}

---------------

Function prototyping declaration : omits the function body but does specify the function’s return type.

#include <iostream>
using namespace std;

int add (int x, int y) ; 

// function prototype
// After this point, any code,including main, can use the add function even though the add
// function is defined later on, below main.

int main ()
{
int result = add( 1, 2 ); // call add and assign the result to a variable
cout << "The result is: " << result << '\n';
cout << "Adding 3 and 4 gives us: " << add( 3, 4 );
}

int add (int x, int y)
{
return x + y;
}

 

Variables storage type

int globalVariable ;

void Fn()
{
int localVariable;
static int staticVariable;
} 

Variables declared within a function are said to be local variable. The variable localVariable doesn´t exist until function Fn() is called. localVariable ceases to exist when the function returns. Only Fn() has access to localVariable.

It is possible to write another function Fn2() with variable localVariable. There will be two different variables called localVariable, one that belongs to the Fn() function and another
that belongs to the Fn2() function. The variables do not conflict - while Fn()
executes, it has access only to its own copy of the result variable, and vice-versa.

A global variable is a variable that is declared outside of any function. These variables are available everywhere in the program past the point of the variable's declaration. globalVariable exists as long as the program is running. All functions have access to globalVariable all the time. 

Global variables makes your code more difficult to understand: to know how a global variable is really used, you have to look everywhere! Using a global variable is rarely the right thing to do. You should usethem only when you truly need something to be very widely available.

The variable staticVariable is created when execution first reaches the declaration. staticVariable is only accessible within Fn(). However staticVariable continues to exist even after the program returns from Fn(). If Fn() assigns a value to staticVariable once, it will stillbe there the next time Fn() is called. 

-------------------------

C

hanging a function argument has no effect on the original variable.
When a variable is passed into a function, it is copied into the function argument:

#include <iostream>
using namespace std;

void changeArgument (int x)
{
x = x + 5;
}

int main()
{
int y = 4;
changeArgument( y );   // y will be unharmed by the function call
cout << y;                   // still prints 4
}


The visibility of a variable is called its scope. The scope of a variable simply means the section of codewhere the variable’s name can be used to access that variable. Variables declared within a function areavailable only in the scope of the function.

int divide (int numerator, int denominator)
{
    if ( 0 == denominator )
{
int result = 0;
             return result;
}
int result = numerator / denominator;
return result;
}

The first declaration of result is in scope only within the if statement’s curly braces. The seconddeclaration of result is in scope only from the place where it was declared to the end of the function.In general, the compiler won’t stop you from creating two variables with the same name, as long as theyare used in different scopes.
....but can be confusing to someone trying to understand the code.

The main use of functions is to make it easy to reuse code. But even if you didn’t need to reuse code, sometimes having a long block of code doing something very specific and complicated can make it hard to understand, and creating a function make the code more readable. 

Naming and overloading function

Choosing good names for functions, variables and just about anything in your code is important—names help you understand what your code is doing.

C++ allows function overloading; you can use the same name formore than one function, as long as the functions all have different argument lists. So we can write:

int add (int x1, int y1, int x2, int y2, int x3, int y3);
and
int add (int x1, int x2); 

 

The compiler can also handle functions with the same number of arguments, as long as the arguments are of different types.

Overloading makes sense if the two functions do the same thing but do it to different arguments.

 

Pointers ------------------------------------------

A pointer is a variable that stores a memory address.

When a variable stores the address of another variable, we‘ll say that it is pointing to that variable.

In order to get access to (nearly) unlimited amounts of memory, we need a kind of variable that canrefer directly to the memory that stores variables. This type of variable is called a pointer.”

“The cool thing is that once you can talk about the address of a variable, you’ll then be able to go to that address and retrieve the data stored in it. If you happen to have a huge piece of data that you want topass into a function, it’s a lot more efficient (when your program is running) to pass its location to thefunction than it is to copy every element of the data—just as we saw with arrays. We can also use thisapproach to avoid copying structures when passing them into functions. The idea is to take the addressthat stores the data associated with the structure variable and pass that address to the function insteadof making a copy of the data stored in the structure.”

memory

One part of memory is used to store the variables that you declare in the functions that are currently being executed—this part of memory is called the stack.

A second part of memory is the free store (sometimes known as the heap), which is unallocated memory that you can request in chunks. This part of memory is managed by the operating system; oncea piece of memory is given out, it should only be used by the original code that allocated the memory—or by code to which that address is provided by the memory allocator. Using pointers will allow us togain access to this memory.

Each piece of memory you have allocated from the free store should eventually be
released back to the free store when your program no longer needs it.

The concept of ownership is part of the interface between a function and its users—it is not explicitly part of the language. When you write a function that takes a pointer, you should document whether the function takes ownership of the memory or not. C++ will not track this for you, and it will never free memory that you have explicitly allocated while your program is still running unless you explicitly request it.

You must always initialize pointers before you use them!   else you can accidentally use invalid memory and will result in either a crash or data corruption.

Hyperlinks and pointers have a lot of the same advantages and disadvantages :
– You don’t have to make a copy.

– You don’t have to worry about whether you’ve got the latest version of the webpage.
- The page might be moved, or deleted.

int x;
int *p_x = & x;
*p_x = 2;            // initialize x to 2

the code :
int *p_x;       // A pointer to an integer
p_x = & x;   // Read it, "assign the address of x to p_int"
may be written with a single line code :
int *p_x = & x;

Using a pointer also requires some new syntax because when you have a pointer, you need the ability to do two separate things:
1) request the memory location the pointer stores
2) request the value stored at that memory location

int x = 5;
int *p_pointer_to_integer = & x;
cout << p_pointer_to_integer;    // prints the address of x , this is equivalent of cout << & x
cout << *p_pointer_to_integer;  // prints 5 , this is the equivalent of cout << x;

The code *p_pointer_to_integer says, “follow the pointer and get the value stored in the memorythat is pointed to”.

 

Structures ------------------------------------------

 Appendix

character constant :

"\n"    newline

"\t"     tab 

""    NULL

"\\"     backslash


 

The Stack

http://www.altdevblogaday.com/2011/12/14/c-c-low-level-curriculum-part-3-the-stack/

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Leave a comment