C and C++ programming

 

Introduction

 

There are two new C++ standards:  C++14/C++11. I advise you to get acquainted with them at https://isocpp.org/ ( ISO C++ Standard )

 

This text was written back in 2005/2006, and still - loosely - works to introduce people to C++, although I keep updating it as much as possible it does aim to teach C++ just stimulate you to overcome the assumption that C++ programming is for a few. I am a living proof that is not.

 

 

The C Language

 

Pointers? If you're afraid of pointers, let me give you a few hints and links. First of all: think of pointers as an arrow pointing to a memory location which is basically what a pointer is.

 

A pointer is nothing less than a variable that stores an address. You could be wondering why? If you're passing a whole struct to a function and will pass it by value ( i.e. not using pointers ) the compiler will have to copy it all.

 

For single parameters, this is not a trouble, but for huge arrays or huge structs,  this might be a trouble. With a few experiences, you start thinking about pointers as addresses and it is less scary with the years.


int i; /*declares a variable of the integer type*/
int *y;/*declares a pointer*/
y = &i;/*y holds the address of the variable*/
int a[10];
y = a; /*you could've made y = &a[0] also */

 

In fact, the pointer "points" by copying the address of the variable. If you increment a pointer, you just tell the compiler to jump to the next memory value. If your pointer points to int or float do not matter as it knows where to go. By the way, do never try a "&yourPointer++", because it will cause you major troubles. Either use:


*(yourpointer+1) = 2;

or

yourPointer++;.
 


Remember that & is the address and * is the content of the pointer. Or & gets the address and * the value we want.

 

Function pointers are also really hard to get IMHO, and it is generally avoided. However, I had to use it often especially when working with threads and DLLs. In C++, if you want to have a generic function, you just use templates. In C, you cannot use it, so you'll have to use function pointers.

 

Say, you have such a function:


void Ovo( int * )
{
/**/
}
 

But you want to pass it a function. How to do it?


int function1( int y )
{
/**/
y = y + 20;
return y;
}
int function2( int y )
{
/**/
y = y + 30;
return y;
}

 

See that both functions have return types and parameters that are compatible to our function pointer. It is then natural to do:



int Ovo( int jaca, int (*functionptr)(int a ) )
{
/*Use functionptr as a shorthand for function1 or function2*/
int inside;
inside = functionptr( jaca );
return inside;
}

int main()
{
int a = Ovo( 2, function1 );
int b = Ovo( 3, function2 );

return 1;
}

 

The statement below is very complicated. :



int Ovo( int jaca, int (*functionptr)(int a ) )/*...*/

 

Ovo is a function that returns an int. Its parameters are an int value and a function pointer. Or, it gets a function that returns an int and has an int parameter ( check function1 and function2 ). Please note that we use the * operator in the prototype/definition of the function and not when we actually use the function. It's not required.

 

Another complex subject is dynamic allocation. Not because it's hard to understand, I don't think so, but if do not "deallocate" memory, perhaps you'll be overloading your memory capacities. C has many functions to allocate memory, and the most used is malloc. It allocates N bytes from the heap, but you'll have to cast it to your desired type as it returns a pointer to char. If malloc returns NULL, you didn't get your goal.

 

#include <stdio.h>
#include <stdlib.h>
struct Example {
unsigned char item1;
int item2;
} ;

typedef struct Example MyStruct;/* always easier to declare a typedef to use structs */

void GetAStruct( MyStruct * );/*prototype to a function that returns void and receives a pointer to a struct*/

int main(int argc, char *argv[])
{
MyStruct ms;
MyStruct *mallocateds;
ms.item1 = 'A';
ms.item2 = 'B';
GetAStruct( &ms );

 

/*does not require the cast, */
mallocateds = malloc( sizeof( MyStruct ) );

if ( mallocateds != NULL )
{
mallocateds->item1 = 0x00;
mallocateds->item2 = 2;
}

free ( mallocateds );
system("PAUSE");
return 0;
}

void GetAStruct( MyStruct * s )
{
/*Do something with the struct you passed to
the function, use the -> operator to access its members */
s->item1 = 0x3A;
s->item2 = 2;

}

 

A few years ago I had to the urgent need of writting a small data structure facility for C. At that time I came up with a more simpler approach, while here I try to write something more complete.

 

The Makefile:

OBJS = hello.o data.o

CC = gcc

DEBUG = -g

CFLAGS = -Wall -c $(DEBUG)

LFLAGS = -Wall $(DEBUG)

INCLUDE = ../inc

 

all: Hello

 

Hello: $(OBJS)

$(CC) $(LFLAGS) -I$(INCLUDE) $(OBJS) -o Hello

 

clean:

rm *.o *.exe

 

 

main.c

#include "../inc/include.h"

#include "../inc/data.h"

 

int main( void )

{

Node Node1;

Node1.Id = 0;

Node1.data = NULL;

initData();

AllocateSegment( 1 );

InsertNode( &Node1 );

return 0;

}

 

Include.h

#include "stdio.h"

#include "string.h"

#include "stdlib.h"

 

data.h

#include "include.h"

 

#define MAX_SEG_SZE 250000

#define MAX_SEG 5

 

typedef struct {

int Id;

void* data;

} Node;

 

typedef struct {

unsigned char seg;

int location;

Node* CurrentNode;

} Cursor;

 

/*

It will hold pointers to every segment, we need to allocate every one of them

Segment1 =

Segment2 =

Segment3 =

:

Segmentn =

*/

typedef Node* Segment;

Segment* Segments[ MAX_SEG ];

Cursor Navigator;

 

inline void SV( int seg, int pos, Node* ptr );

void initData( void );

void dealallocateseg( int n );

 

int InsertNode( Node* ptr );

int AllocateSegment( int n );

int isSegmentFull( int n );

int getNumberOfSegmentsAllocated( void );

 

Node* GetCurrentNode( void );

 

 

 

Data.c

 

#include "../inc/data.h"

 

inline void SV( int seg, int pos, Node* ptr )

{

Navigator.seg = seg;

Navigator.location = pos;

Navigator.CurrentNode = ptr;

}

void initData( void )

{

memset( Segments, 0x00, sizeof( Segments ));

SV( 0, 0, NULL );

}

 

int AllocateSegment( int n )

{

if (( n < 0 )||( n > MAX_SEG ) )

return -1;

/*

we allocate memory for MAX_SEG_SZE nodes

*/

Segments[n] = malloc( sizeof( Node* )* MAX_SEG_SZE );

if ( Segments[0] == NULL )

return -1;

SV( n, 1, NULL );

return 0;

}

 

void dealallocateseg( int n )

{

if ( Segments[n] != NULL )

free( Segments[n] );

}

 

int isSegmentFull( int n )

{

if ( n < 0 )

return 0;

/* See if it matches the current segment*/

if ( Navigator.seg == n )

{

if ( Navigator.location > MAX_SEG_SZE )

return 1;

}

return 0;

}

 

int getNumberOfSegmentsAllocated( void )

{

 

return Navigator.seg;

}

 

int InsertNode( Node* ptr )

{

if ( ptr == NULL )

return -1;

if ( isSegmentFull( Navigator.seg ) == 1 )

{

/*Current segment is full we need to get to next*/

AllocateSegment( Navigator.seg );

}

Segments[ Navigator.seg ][ Navigator.location++ ] = ptr;

return 0;

}

 

Node* GetCurrentNode( void )

{

return Segments[ Navigator.seg ][ Navigator.location ];

}

 

 


 

The C++ Language 

 

The transition from C to C++ is not obvious, I think it is fairly clear why. The only method I know to go through this process smoothly is to write code, laboriously and patiently. 

 

C++ supports ( among others ) a paradigm called "Object Oriented Programming", which makes use of classes, encapsulation, polymorphism, etc. Again, be sure to use a book or good tutorial that's ANSI C++ compliant otherwise you will find some troubles. 

 

(By the way, Bjarne Stroustrup has a great tip to detect if a tutorial or book is compliant: if the author's main function return void, discard it.)

 

I highly recommend  http://www.cplusplus.com - which has been also updated to C++11/C++14.

 

I really recommend the book "Sams Teach your self C++ in 24 hours", this is the book to start learning C++.  The other strong recommendation I would like to mention is "Programming Principles And Practices Using C++" by Stroustrup, which is a masterpiece in the same level as K&R.

 

After these two, Bjarne Stroustrup's 4th edition of "C++ Programming Language", which is by definition, the greatest and most important C++ canon. But I admit that is not a simple read and it is very expensive. and it works more effectively as a desktop reference ( and to scare Java programmers away ;-) ).

 

Bjarne Stroustrup has also released the excellent "A Tour Of C++" but that is not for novices too albeit rather simpler than the above, it is a very good reading for programmers that want to learn C++ but have a background in other languages like C or C#. 

 

I really like Scott Meyers "Effective C++" and "Effective Modern C++", not to read from to cover to cover though.

 

One of the most powerful features in C++ are templates and STL. There are several data containers that can be used. Programmers need not worry to implement linked lists or queues. Programmers already have easily at hand several algorithms for searching, sorting etc. The limits of STL these days lie where on how much you know it.

 

It is ok, of course, if you want to ignore this tip and write your own libraries for this but it will be a waste of time.

 

The STL strings, they are usually found under the header <strings>, and usually noted std::strings are very useful. They will save a lot of time and they are faster enough to make you forget ANSI C NULL-terminated strings.

 

The C++11 and C++14 new features not just make it C++ more appealing but faster and safer. Smart pointers, auto types, lambda functions, move constructors, etc.

 

 

Maybe this will help you...

 

I have been working with a small development framework for LINUX/UNIX, with support for threads, sockets, sqlite, logs and factory classes.

 

You can download the package at https://goo.gl/kVRQD6.

 

Speaking of frameworks, my favorite one is QT:

 

https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=2ahUKEwjCucPU77zcAhUIXK0KHS4TAJkQFjAAegQIBRAC&url=https%3A%2F%2Fwww.qt.io%2F&usg=AOvVaw3TZB5vUBtw1OZgGg4vte0k

 

However, it's a paid software should you want to use it for commercial purposes. The best thing is that Qt includes many libraries and it is very easy and fast to migrate software from platform to another.