LABORATORY 01

Introductory Concepts for the C/C++ Languages

Duration: 2 hours Language: C / C++ Environment: Code::Blocks / Visual Studio / GCC PDF handout RO versiunea română

The first session clarifies what happens between the moment we type text into an editor and the moment the computer executes a program. Understanding the four stages - writing, compiling, linking, execution - explains most of the errors you will run into for the rest of the semester.

1Lab objectives

  • Installing and configuring a C/C++ development environment
  • Following the four stages through to a working executable file
  • Telling compilation errors apart from linking errors
  • Recognizing syntactic units: identifiers, keywords, operators, constants
  • Writing, compiling, and running your first program

2Working environment

  • IDE Code::Blocks or Visual Studio
  • C GCC / MinGW compiler
  • C++ G++ compiler
  • alt. Text editor + command line
Compiling from the command line If you want to see the stages explicitly, use the terminal: gcc program.c -o program.exe then ./program.exe

3The stages of producing an executable

Source program .c / .cpp Compiler + preprocessor Object code .obj / .o Linker + libraries Executable .exe A compile error stops the process before the object code; a link error only shows up at the next step.
Fig. 1 - The main stages gone through to produce an executable program
StageWhat it doesResultTypical errors
Writingwriting the code in an editor or IDE.cpp file-
Preprocessingexpands #include and #defineexpanded source codeheader file not found
Compilationtranslates the source into machine code.obj filewrong syntax, incompatible type, undeclared variable
Linkinglinks object modules and libraries together.exe filefunction declared but not defined, missing main
Executionloads the program into memory and runs it-division by zero, invalid memory access
How to tell which stage you got wrong in A message pointing to a line number in your file is a compilation error. A message like undefined reference to ..., with no line number, is a linking error: the function was declared, but its body was not found anywhere.

4Basic elements of the language

Writing a program uses syntactic units that fall into a few categories:

CategoryDescriptionExamples
Identifiersnames given to types, variables, functionsradius, _maxx, a5, A_B_C
Keywordsreserved identifiers, with predefined meaningint, while, return, class
Punctuation marksdelimit regions of code[ ] ( ) { } , : ; #
Whitespaceseparators, improve readabilityspace (32), tab (9), newline (10)
Operatorsspecify the operations performed+ - * / % = == &&
Constantsfixed values, numeric or strings23, 3.14, 'A', "text"

Rules for identifiers

IdentifierValid?Reason
Radiusyesstarts with a letter
radiusyesdifferent from Radius - the language is case sensitive
_maxxyescan start with an underscore
a5yesthe digit is not in the first position
5anothe first character is a digit
A%Bno% is not an allowed character
Case sensitiveC/C++ distinguishes between uppercase and lowercase. Total, total, and TOTAL are three completely distinct variables. This is a frequent source of "undeclared variable" errors for beginners.

5Program structure

The general structure of a program is made up of three zones:

ZoneContentsMandatory?
I - preprocessing directives#include, #defineoptional
II - global declarationstypes, function prototypes, global variablesoptional
III - function definitionsfunction bodies, including main()mandatory
The main() functionProgram execution always starts with main(). It is unique and cannot be overloaded. Unlike Pascal, in C/C++ functions cannot be defined one inside another.

6The first program

first.c - the C version
#include <stdio.h>        // zone I: preprocessing directives

#define PI 3.14159         // symbolic constant

int runCount = 0;          // zone II: global variable

int main(void)             // zone III: definition of the main function
{
    float radius, area;    // local declarations

    printf("Enter the radius: ");
    scanf("%f", &radius);

    area = PI * radius * radius;

    printf("Circle area = %.2f\n", area);

    return 0;              // 0 = program finished successfully
}
first.cpp - the C++ version
#include <iostream>
using namespace std;

const double PI = 3.14159;   // in C++, const is preferred over #define

int main()
{
    double radius, area;

    cout << "Enter the radius: ";
    cin >> radius;

    area = PI * radius * radius;

    cout << "Circle area = " << area << endl;

    return 0;
}
The key differenceIn C, input/output is done with functions (printf, scanf) that take an explicit format. In C++, streams are used (cout, cin), and the type is deduced automatically by the compiler - safer and more convenient.

7Code workshop

Here you can write and run C code directly on the page. The program runs in the browser, with no compiler installed: press Run and watch the output below. The Step by step button executes the program instruction by instruction and shows, on the right, the value of each variable at that moment.

The structure of a C program - run it, then change it
#include <stdio.h>

int main(void)
{
    printf("Hello, world!\n");
    printf("My name is %s and I am %d years old.\n", "Ana", 19);
    return 0;
}
Try thisTry removing \n from the first printf and run it again. Notice that the two lines end up on the same line - \n is the only thing that moves the cursor to the next line.
Exercise - print a business card
#include <stdio.h>

int main(void)
{
    /* Complete the program so it prints exactly what you see
       in the "expected output" column.
       You will need four printf calls. */

    printf("+----------------------+\n");

    return 0;
}

8Work tasks

  • Install the development environment and create a new console application project.
  • Write, compile, and run the program that computes the area of a circle.
  • Intentionally delete a ; character and read the error message - note the line indicated.
  • Call a non-existent function (for example compute();) and observe that the error occurs at link time, not at compile time.
  • Check that the language is case sensitive: declare int sum; and use Sum.
  • Test which of the identifiers in the table above are accepted by the compiler.
  • Write the same program in both versions, C and C++, and compare the size of the resulting executable.

9Extended application

ExtensionWrite a program that reads the radius and prints, in an aligned table, the circle's area and circumference, and the sphere's surface area and volume. Use #define for PI and %8.3f formatting for alignment. Compare the results with those obtained using M_PI from <math.h> and explain any differences.

10Review questions

11Resources