Basic C/C++

C is a powerful programming language, but it is pretty symbolic and not easily understood. For you Java programmers here are some of the basics of C/C++ for a hello world program that can add some numbers. If you can use g++ compiler as that will give you the least problems.

The command to compile all the cpp files in a directory is g++ *.cpp

After that you can ./a.out to execute the program.

If you are using Eclipse IDE as a front end for your compiler and are getting a binary not found error when you try to run the program first click the menu item… Project – build project – and that should fix your run. “Build all” which seems like it would work doesn’t. You have to use “build project if it is a new project.” If that doesn’t fix it try menu item Run – Run Configurations – and on the left hand side menu select your programs debug and then in the right hand menu in the Main tab select “Enable auto build” instead of “Use workspace settings” and there you go.

Most common solution however is click PROJECT:PROPERTIES:RUN/DEBUG SETTINGS (delete anything listed there if you think it’s interfering) then click NEW:C/C++Application then OK then make sure “Use workspace settings” is selection and click okay. Now try Building Project and running again.

If you are still having trouble your run or debug configurations may be pointing to the wrong directory or file when the run or debug is launching. Check both Run-Run Configurations and Debug Configurations to make sure they are pointing to the correct directory when executing the run and debug files. The compiler makes separate files for testing and debugging. The debug file will probably have a *.d name and the run a *.o filename.

Each file should be named Filename.cpp with a capital first letter.

A library is a collection of functions from another c program, just like a class in java, and so can be used in your program. In java we use import. But in C we use #include <>.

And as a shortcut so we don’t need to type std::cout all the time we can use something called “using namespace” which basically forces the program to use an abbreviation if at all possible. The difference here is using a fully qualified (verbose) name or the unqualified (abbreviated) name. Either one is fine as long as you include the line “using namespace std;” to eliminate the necessity of using a fully qualified name. This is called namespace aliasing.

Your primitive variable types are:

char,char16_t,chat32_t,wchar_t for working with characters.

signed char, short, int, long, long long, for signed integers.

unsigned char, short, int, long, long long for unsigned interger.

Floating: float, double, long double

Boolean: bool

void

and for null pointer… decltype(nullptr)

The syntax for declaring a variable is the same as java. int a = 1; will do.

The difference however is in strings. A String is java is not a primitive data type, but rather a class and so the word “String” must be capitalized in java. In c it is a real primitive and so is not. string mystring = “hi”; will do but you can also use parenthesis like string mystring = (“hi”) like we do in java.

Constants can be declared like const int a = 1; or with #define a = 1;

Recasting a float to a int is as simple as:

float b = 3.14;

a = (int) b;

Using << and >> directs input output from standard in and out like:

std::cout << “Hello world”;

Basic functions/methods are called the same as in java. The syntax for declaring a method (called a function in C) is return type, name,parameter list and then braces. We can include the word static if we want but the main function can not be static, unlike java where it must be. You should, but are not required, to put a return 0; statement in your main function. Just like java class variables (field variables) are simply those declared outside of a function/method so their scope is global, and they can be static or not.

Anything marked with a # sign is a directive to the compiler’s preprocessor.

Array declarations are different than in java. “int myarray [3] = {1,3,2,63}”, will do.

A basic c program is called a C structure, a class is a C structure with some private functions/members/data, etc.

Example helloworld.cpp

#include <iostream>
using namespace std;//allows for cout << instead of std::cout <<;
//these lines…
//std::cout << “Hello world”;
//and
//cout << “Hello world”; are the same if using namespace std;

int addnumbers(int a, int b){
    return a + b;
}

int main() {
    cout << “!!!Hello World!!!” << endl; // prints !!!Hello World!!!
    cout << addnumbers(1,2) << endl;
    return 0;
}

The most basic output however is with the printf function in the stdio library.

#include <stdio.h>
int main(){
printf(“Hi\n”);
}

 

Now let’s look at pointers. The most confusing thing about C. When we want to refer to a memory’s address in which a value is stored we use & like…

a = &b;

This would store the memory address of b in a.

If we want the value however of b and not it’s address we can grab it directly with a dereference operator which is the asterix * like this…

a = *b;

which would store the value of b into a.

The problem is you have to declare the variables correctly like this..

int a = 12;
int * b;
b = &a;
cout << b;

that would work and would print out the address of a.

There is an explanation of how this relates to arrays and functions here… http://www.cplusplus.com/doc/tutorial/pointers/

Once you understand a little about pointers a program like this will make more sense…

#include <stdio.h>
int main(){
char myname[15];
printf(“Enter your name…”);
scanf(“%s”, &myname);
printf(“Oh so your name is %s”, myname);
return 0;
}

Explanation: The datatype char stores a single character, by declaring it as an array with brackets [] and setting the length of the array as 15 we provide space to store a string. Strings are real primitives in C unlike in Java. They are just char as an array.

The printf statement is like System.out.print(“”); in Java. It just sends data to std out (the computer monitor.

The scanf statement gets a scanner which is a class in java, but just a function/method in C as long as #include <stdio.h> is used. The scanner puts up input from the users keyboard from std in. The function is passed the parameters of a string which includes a “%s” use. That means that the next bit of information should be stored as a string. The % symbol catches the attention of the compiler to look at the next character as an instruction about how to format the information being sent to it. If we wanted to gather a number from the user instead of a string we could have used %d. The &myname means to store the information in the ADDRESS of the character array called myname which we declared before. That’s how pointers are especially useful in C. They allow us to bridge the gap between char data types and strings. The entire string will be shoved into the address of the variable one character at a time filling up that memory space. Crazy huh?

The next printf is pretty standard, but again note the %s telling the computer to display the variable we will pass it as a string and then we give it the variable’s name. No need to use pointers here because the data is already stored and as long as we format it as a string the char array will display as a string just fine. Crazy but true.

Writing basic classes/types… Data in a class is called a member, and the code that controls them is called a function (a method in java).

The syntax for a class declaration is keyword class (lowercase) followed by it’s name beginning with upper case, followed by a braces set and then terminated with a semi-colon. Like this…

class MyClass{};

placement functions and data members is basically the same as java but the syntax for declaring a function/method is a bit different (see above)…

to declare an object instance of a class in code use…

MyClass myobject;

To assign a value to a global variable in a class…

myobject.a = 1;

Or to do that in a setter scheme…

myobject.setA(1);

with a function in MyClass like this…

void setA(int x){

a = x;

}

But remember that in C++ all global class data (member data) is private by default so you have to declare it as public to access it in this way since…

class MyClass{

int a;

};

would not allow public access to a, instead you need…

class MyClass{

public : int a;

};

And the full class could be…

class MyClass{

public : int a;

void setA(int x){

a = x;

}

};

By default variables are signed. You can change it to unsigned if desired.

Now you can do.

MyClass Myobject;

Myobject.a = 1;

You can group all the public declarations together like…

class MyClass{

public :

int a;

string g;

};

Remember to terminate the grouping properly.

To call a method within a class object…

Myobject.MyFunction();

To call a single instance use…

void MyClass();

But this is pretty useless most of the time in C++ from what I can tell. Most things should be done by creating an object first. If you however create a function that is always called through the class’s constructor that might work. But again that is sloppy. But there is a way to do it through static function declarations…

#include <iostream>
using namespace std;

class MyClass{
static void saySomething(string s){
cout << s;}
};

The function saySomething could be called now as a static (a single instance invocation) with the line…

MyClass().saySomething(“Hello World”);

from the main program. And there you go!

To make sure your class will be linked with the main program you have to include it like this…

#include “MyClass.cpp”

Notice the difference between using <> and “” for includes. <> is used for standard library stuff and “” for custom classes.