Pengetahuan Dasar C/C++

From SmartCommunity

Jump to: navigation, search

First of all, you need to have a working C/C++ compiler. You may use gcc/MinGW or Microsoft Visual C++. The compiler translates source files into object files that contain machine code and have extension “o”. Each source file is compiled into an object file, then the object files get linked using some linker. Let’s see a short example that shows the primary basics.


First C program

Let’s see the first example.

include <stdio.h>

int main() {
 printf("Hello, world!\n");
 return 0;

It’s a very basic pure C program that prints “Hello, world!” on the user’s screen and appends end of line ("\n") character. We used header file stdio.h that defines such function as printf. This function is commonly used for formatted output of various data: strings, characters integer and floating-point numbers. We have defined our own function named main which is so-called program entry point. Each program has it’s entry point — function that is launched when the user runs the application. The result type of this function is usually int — it allows to give operating system information about the program’s execution status: 0 means success, any other number means some error code.


Identifiers are program entity names. They are used for functions, variables, classes and more. An identifier is a sequence of letters and/or digits starting with a letter that may also contain sign “_”. Some examples of valid identifiers are: foo, bar, baz1, my_blah. An identifier may start with “_”, but it is not recommended.


Variables are names that point to some data stored in memory. Each variable has it’s own name which is an identifier, and data type. The most common data types in C language are:

  • int represents integer numbers from -32768 to +32767
  • char represents ASCII characters, but also is an integer data type representing numbers from -128 to 127
  • float represents floating-point numbers
  • double represents floating-point numbers with better accuracy

Additional modifiers for data types are unsigned, long and short. Examples:

  • unsigned int represents integer numbers from 0 to 65535
  • long int represents numbers from -2147483648 to 2147483647
  • unsigned short int represents numbers from 0 to 255

When using additional modifiers, it’s possible not to append “int” to them and use modifiers as type names. Examples:

  • unsigned long is the same as unsigned long int

Modifier “long” may be applied twice:

  • unsigned long long int

Each variable should be defined in the program before it’s usage. Let’s try to use variables in a simple example.

include <stdio.h>

int main() {
 unsigned short int a = 5;
 long b;
 b = 9;
 printf("%d", a + b);
 return 0;

This example is a little more complex than the previous one and some parts of it will be described later. Now please note the correct syntax of variable definition:

datatype identifier

Useful links