Structure of C programs. Basics of the C language: structure of a C program, basic types and construction of new types, operations and expressions
Structure of a program in C language.
Using the C programming language in solving economic problems
Programs and data
Advantages of the C language
1) C – modern language, its structure encourages the programmer to use methods in his work: top-down design, structured programming, modular program structure.
2) C – effective language. C programs are compact and fast to execute.
3) C – portable or mobile language.
4) C is a powerful and flexible language.
5) Programs written in C are used to solve problems different levels. C has a number of powerful assembler constructs.
6) C is a convenient language, it is structured and at the same time does not limit programmers’ freedom too much.
7) C is a compiling type language. Since C is standardized, hardware-independent, widely accessible language, an application written in C can often run with minimal or no modifications on a wide variety of computer systems. The computer, despite its speed and computing power, is simple device, which manipulates binary numbers. Alone binary numbers are interpreted by the computer as commands, others as data. To make a computer do anything useful, you need to write a program.
Programming – program development activities.
Program is a description of an algorithm for solving a problem specified in a computer language.
Team – an order defining the next step.
Example teams: C=A+B, where A, B are operands, + is the operation.
Operation - this is what the computer must do according to each command.
Operands - participants in the operation, what and with what the operation is performed. A set of elementary operations from the methods of their descriptions form a system of programming language commands.
Example #1:
#include
(void main(void) //header of the main function of the program
сout<< “Здравствуй, С!\ n”;
1 line: connecting auxiliary libraries focused on input and output of data of different types into a stream.
2nd line: header of the program's main function. Cout operator for outputting information<< – помещение в класс данных, \n-переход к новой строке вывода.
Program is a sequence of instructions that implement an algorithm; a set of instructions that uniquely determine the content and sequence of operations to solve problems.
Use of S.
1. Programs and data.
2. Scheme of program execution on a computer:
Example #1:
#include< stdio.h>
printf ("I study at BSUIR\n");
Line 1: The include preprocessor command includes the stdio.h file, which describes the printf library function.
Line 2: definition of a function called main that does not receive any arguments. The main statement is enclosed in curly braces. The main function calls the printf library function to print the specified sequence of characters. Slash (\n) - newline character, transition to a new line.
To execute the program on a PCEM, you must do the following:
1) Create a program in a programming language.
2) Translate it in the standard of this language.
3) Link it with the necessary programs and functions.
4) Load into RAM.
5) Execute and get the result.
COMPLETION SCHEME
A translator is a computer program for translating a program written in a programming language into a form understandable for a computer. The compiler output is a file with the extension obj. An executable file, or load module, is a file that contains a program compiled and ready to be executed. Borland C++ is a program development environment that includes both a compiler and some other tools.
Program structure in C language.
Any C program consists of one or more functions and elements. The various functions can be given any name. Functions contain instructions (commands) that prescribe actions at a specific execution step, and a variable stores values used during these actions. Such actions can be assigning values to variables or checking some condition. A function named main. The execution of any program begins with the main function.
a) General structure of a C program without recourse to a subroutine:
b) General structure of a C program with reference to the subroutine:
Arguments are one of the mechanisms for interaction between functions. A list of arguments in parentheses follows the function name. Curly braces mark the beginning and end of a program. Instructions that make up the program body of operators and operands. In C, every statement and every line calling a function ends with a semicolon. The exceptions are preprocessor commands and function names at the beginning of a program unit. The goal of most programs is to solve a problem through various transformations of the source data. For this it is necessary.
Last update: 05/18/2017
A C program consists of a set of preprocessor directives, function definitions, and global objects. Preprocessor directives control the transformation of text before it is compiled. Global objects define the data used or the state of the program. And functions define the behavior or actions of a program. The simplest C program, which was defined in previous topics:
#include
Instructions
The simplest building block of a C program is statements. Each instruction performs a specific action. In the C language, statements are ended with a semicolon (;). This sign indicates to the compiler that the instruction has completed. For example:
Printf("Hello world!");
Calling the printf function, which prints the string "Hello world!" to the console. is an instruction and ends with a semicolon.
A set of instructions can represent a block of code. A block of code is formatted with curly braces; the instructions that make up the body of this block are placed between the opening and closing curly braces:
( printf("Hello world!"); printf("Bye world!"); )
There are two instructions in this block of code. Both instructions represent a call to the printf() function and print a specific string to the console.
Preprocessor Directives
To output data to the console in the example above, the printf() function is used, but in order to use this function, so that it is generally available to us in the C program, it is necessary to include the stdio.h header file at the beginning of the source code file using the include directive.
The include directive is a preprocessor directive. In addition to this include, there are a number of preprocessor directives, for example, define.
Each preprocessor directive is placed on one line. And unlike normal C language instructions, which are terminated by a semicolon; , a sign of completion of a preprocessor directive is translation into new line. Additionally, the directive must begin with a pound sign #.
The "include" directive directly determines which files should be included at a given place in the program text. By default, we can include standard files from the directory of so-called "header files", which are usually supplied with the compiler's standard libraries. And the file "stdio.h" is just one of these header files.
In general, the term “header file” itself implies the inclusion of the text of the file at the beginning or header of the program. Therefore, header files are usually included at the beginning of the source code. In addition, the header file must be included before calling the functions it defines. That is, for example, the file stdio.h stores the definition of the printf function, so this file must be included before calling the printf function.
But in general, preprocessor directives do not have to be placed at the beginning of the file.
When compiling source code, the preprocessor first runs and scans the source code for lines that begin with the # character. These lines are treated by the preprocessor as directives. And in place of these directives, the text is converted. For example, in place of the #include directive
main function
The starting point for any C program is the main() function. It is with this function that the execution of the application begins. Its name main is fixed and is always the same for all C programs.
A function is also a block of code, so its body is surrounded by curly braces, between which there is a set of instructions.
It is worth noting that modifications of this function can be found in various literature and examples. In particular, instead of the definition above, we could write it differently:
#include
#include
Using these definitions would not be an error, and the program would also print the string "Hello world" to the console. And for most compilers this would be fine.
Next we will take a closer look at the definition of functions, but here we need to take into account the following aspect. The definition of a function in the form int main(void) is fixed in the C11 language standard. Compilers primarily focus on the language standard, its specification. Therefore, if we use the definition given in the language standard, then there is a greater chance that it will be supported by all compilers. Although, again, I repeat, there will not be a big mistake in using the second option or int main().
The full latest C11 standard can be viewed at
Any program written in the C language consists of one or more “functions”, which are the main modules from which it is assembled.
An example of the structure of a simple C program:
General view |
Example |
preprocessor directives |
#include # define N 10 |
main function name | |
start of the main function body | |
declarations of variables and arrays |
int x=1; char str[N]; |
program statements |
puts("Enter Name"); gets(str); printf("\n %s, you are %d my guest!",str,x); |
End of main function body |
Preprocessor Directives
Part of the compiler is a program called preprocessor. The preprocessor works before the program is translated from a high-level language to machine language, performing its preliminary conversion. Each preprocessor directive begins with a # (number) character and spans the entire line. Directives that do not fit on one line can be continued on the next line. The line continuation sign is the backslash character (\) in the line to be continued.
The most commonly used directive is to include a file in a program
# include < name>
Where name– the name of the file included in the program text.
This directive is called substitution directive . It instructs the compiler to place the file in its place name. File name called header. It contains declarations of data and functions used in the program. For example, including in the program the directive
# include < math. h>
will allow you to use standard mathematical functions in the program, such as sin x, cos x, ln x, etc. A list of standard mathematical functions will be given below.
Directive
# include < stdio. h>
makes it possible to use standard input/output functions in the program.
Another commonly used directive is the definition directive
#define S1 S2
Where S1, S2– character strings.
The preprocessor finds a string of characters in the program text S1 and replaces it with the string S2 . For example, including in the program the directive
# define P printf
allows you to type a letter on the keyboard P instead of a word printf.
This replacement is not performed inside text strings (literals), character constants and comments, i.e. action of the directive # define does not apply to texts delimited by quotation marks, apostrophes and those contained within comments.
Main function
Every C program must contain a function declaration main(), which is called the main function . Typically, this function has no parameters and does not return any value. The word used to indicate this fact is void. Thus, the line with the name of the main function usually looks like:
void main(void)
void main()
Variables and Arrays
An array is a group of variables of the same type with a common name. The name of a variable or array is an identifier - a sequence made up of characters:
a – z, A - Z, 0 – 9,_(underline),
Moreover, the first character cannot be a number. Lowercase and uppercase characters of the Latin alphabet are perceived as different characters. C language function words cannot be used as a variable or array name. The main function words of the C language are given in the Appendix.
The array elements are distinguished by their numbers (indices). The index can only accept non-negative integer values. The index is written after the array name in square brackets. There can be several indexes. In this case, each index is written in its own square brackets.
Variables and arrays of various types can be used in the C language. Each type of data takes up a certain number of bytes of memory and can take values from a certain range. The volume of this memory and, accordingly, the range of accepted values in different implementations of the C language may vary. The number of bytes of memory occupied by a variable of a certain type for a specific implementation of the C language can be determined using the operation sizeof(type). For example, you can determine the amount of memory allocated for an integer type variable like this:
k = sizeof(int); printf(“Under a variable of typeint%d bytes of memory are allocated”,k); |
These guidelines discuss three main types of variables and arrays and provide typical values for the amount of memory occupied and the range of values (Table 1):
Table 1
Type Specifier (Keyword) |
Meaning |
Size memory (byte) |
Range of values |
|
Integer number |
32768 . . . +32767 |
|||
2147483648 . . . +2147483647 |
||||
Valid |
Real number |
3.4ּ10 -38. . . 3.4ּ10 38 (modulo) |
||
Symbolic |
128 . . . +127 |
Let's take a closer look at the type variable char. As can be seen from table. 1, type variable char takes up one byte of memory. One byte of memory can contain either an unsigned integer from the range , or a signed integer from the range [–128, 127]. This number is the code for one of 256 characters. The character corresponding to a given code is determined by the code table used. Thus, the value of a variable like char can be treated either as an integer or as a character whose code is equal to that number.
Fig.1 Program structure in C language.
Internal program structure
Executable program in C consists of 4 parts: command area, static data area, dynamic data area, stack area. see Fig.2.
1. The command area contains machine commands; instructions that the microprocessor must execute.
2. Static data area for storing variables with which the program works;
3. Dynamic data area for storing additional data that appears during program operation (for example, temporary variables).
4. The stack is used to temporarily store data and return addresses from functions.
function body/*function body*/
printf("Hello World!");
1st line – a directive that includes the standard input/output header file. There are few operators in C, but there is a library of functions. To use them you need to connect them, which is what the directive does - the 1st line of the program. The # symbol indicates that the string should be processed by the C language preprocessor.
2nd line – name of the main function main(), this function does not return any parameters (I will talk about this a little later). A C program always has a function main(). The execution of the program begins with it.
3rd line – the beginning of the function body. () define the body of the function (in Pascal these are begin and end)
4th line – a comment, it is not compiled, but only explains what is being done.
5th line – library function – print on the screen, the expression in brackets on this line is a function parameter, it is always quoted.
; - this is a sign of the C operator, it is part of the operator, and not an operator separator, as in Pascal.
Tips on how to make a program readable:
1) Choose meaningful names
2) Use comments
3) Use empty lines to separate one part of a function from another
4) Place each statement on a different line.
BASIC ELEMENTS OF THE C LANGUAGE
Let's consider the required elements with which a C program should be designed:
1. Comments – used to document the program. Any program must contain comments: what algorithm is used, what the program does...
Ø 1 way: /* Text */ - anywhere in the program.
As soon as the compiler encounters /**/, it skips them. The compiler ignores /* */ because it cannot interpret a language other than C. That is, if you want to exclude some line from compilation, then enclose it in /**/.
Ø Method 2: if the comment is large, then use this type
/* Line 1 - for a comment of any length
line 3*/
Ø 3 way: // - text to the end of the line.
2. Identifier is a name that is assigned to an object (variable). Upper and lower case letters, numbers and underscores are used. Lowercase and uppercase letters are different. (They do not differ in BASIC). If you call a variable name, Name or NAME, then these will be different variables.
Identifiers begin with a letter or an underscore. For example, _name. But it is not recommended to start with _, since this character is used for global names in the C language.
IN modern programming often used to create identifiers is Hungarian notation, where certain characters are used to characterize the identifier, for example:
b – byte; ch – single-byte character;
w – word; f – flag;
l – long word; fn – function;
u – unsigned; p – pointer;
с – counter; d – difference of two pre-x
cz – string; etc.
3. Function words - these are words with which certain semantic meanings are rigidly associated in the language and which cannot be used for other purposes. These are the names of operators, library functions, preprocessor commands, and so on. These words cannot be used to create names of your functions, variables...
DATA IN SI PROGRAM
Each program operates with data. They are present in the program in the form of variables and constants.
Data that can change or be assigned a value during program execution is called variables.
Data that is set to specific values and retains its values throughout the program's operation, are called constants.
Constants
Constants are fixed values. The value, once set, does not change anymore. Constants come in different types. The types differ in the principle of placement in computer memory, and for a person in the type of recording. There are 7 in C keywords, used to indicate various types data: int, long, short, unsigned, char, float, double.
Types of constants :
a) Integers and long integers . They are written in decimal, octal and hexadecimal number systems. They can be signed or unsigned.
Decimal system: integer constants occupy 16 bit memory, and take a range of values: -32768 to +32767 (2 15) . If the constant is unsigned, then the range is doubled: 0 to 65535(due to the fact that the 15th digit - signed - is used for the number). The suffix is used to denote an unsigned number u (unsigned), for example 123u.
If the number is greater than 40000, then the compiler will automatically convert it to negative number, so the suffix u required:40000u. In the 123u example, the compiler doesn’t care whether there is a suffix or not, since this number is in the range 32767.
Long integer takes 32 bits , value range
± 2147483648 (signed long – long). If you put the suffix l, then, despite the number, 32 bits will be occupied. For example: -5326 l
0 – 4294967295 unsigned long- (unsigned long). The range is increased by the 31st bit. Suffixes used ul eg 32659ul.
If a number begins with the digit 0, it is interpreted as an octal number
16 bits 0 ¸ 077777
0100000 ¸ 0177777u
32 bits 0200000 ¸ 01777777777l
020000000000 ¸ 037777777777ul
If a number begins with the character 0x, then it is interpreted as hexadecimal
16 bits 0x0000 ¸ 0x7FFF
0x8000 ¸ 0xEFFFu
32 bits 0x10000 ¸ 0x7FFFFFFFl
0x80000000 ¸ 0xFFFFFFFFul
b) Real constants. These are floating point numbers. The value has a fractional part. By default, all real constants are of double precision type double . Occupies memory 8 bytes (even if 0.0). Range of values ±1*10 ±307 , can also be written in scientific form, for example: 0.5e+15 or
1.2e-3=1.2*10 -8 =0.0012.
You can force the format to be single precision float . The number will take 4 bytes , the suffix is used f(5.7 f). Accordingly, the range narrows ±1*10 ±37
And also extended accuracy – long double – 10 bytes . (3.14L)
The + sign can be omitted. It is allowed to omit either the decimal point or the exponential part, but not both (.2; 4e16). You can omit writing the fractional or whole part, but not at the same time (100.; .8е-5)
c) Symbolic constants. This is a set of characters used in a computer.
Divided into 2 groups: printed and non-printed(control codes). A character constant includes only 1 character, which must be enclosed in apostrophes and takes up 1 byte memory.
Any character has its own double representation in the ASCII table. In the program, character constants are entered in single quotes; during compilation, the numeric value of the character from ASCII is substituted into the program. One character takes up 1 byte.
Character "A" "a" " " "\n"
Its code is 65 97 32 10
How whole type data "A"=0101 8 , 01000001 2 , 41 16 , 65 10 . There is no need to remember codes.
Control codes begin with a \ character and are also enclosed in apostrophes. The most common control codes are:
\n – go to new line
\t – tab (shifts the cursor by some fixed value)
\b – step back (shift one position back)
\r – carriage return (return to the beginning of the line)
\f – form feeding (feeding paper onto 1 page)
\’ - apostrophe
\” - quotes
The last three characters may appear symbolic constants, and also used in the printf() function, so using them as characters may cause an error. For example, if we want to output the string “The character \ is called a slash,” then the operator should look like this:
printf("The character \\ is called a slash");
a) String constants - contain a sequence of 1 or more characters enclosed in " ". 1 byte is spent for any character + 1 byte for the so-called zero character - a sign of the end of the line. The zero character is not the number zero, it means that the number of characters in the line (N) must be 1 byte more (N+1) to indicate the end of the line (the compiler adds it automatically). For example: “text line” takes up (13+1) bytes;
"World" -
Before you start writing programs, you need to study the structure of programs in the C++ programming language. In other words, program structure is the layout of the workspace (code area) in order to clearly define the main program blocks and syntax. The structure of programs differs slightly depending on the programming environment. We focus on Microsoft IDE Visual Studio, and therefore example programs will be shown specifically for MVS. If you're using another IDE, you'll have no problem porting code from MVS to other development environments, and you'll eventually figure out how to do it.
Program structure for Microsoft Visual Studio.
// struct_program.cpp: Defines the entry point for the console application. #include "stdafx.h" // here we connect all the necessary preprocessor directives int main() ( // the beginning of the main function named main // your program code }Line 1 talks about the entry point for the console application, which means that this program can be launched via command line Windows by specifying the program name, for example, struct_program.cpp. Line 1 is a one-line comment, as it begins with the characters //; we will talk more about comments in the next article. Line 2 includes the header file "stdafx.h". This file is similar to a container, since it contains the main preprocessor directives (those included by the compiler when creating a console application), and auxiliary directives (connected by the programmer) can also be connected.
include is a preprocessor directive, i.e. a message to the preprocessor. Lines starting with the # symbol are processed by the preprocessor before the program is compiled.
Preprocessor directives can also be included in lines, starting after the #include "stdafx.h" entry before the start of the main function. Moreover, this method of connecting libraries is the main one, and using "stdafx.h" is additional opportunity connecting header files, which is only available in MVS. From lines 4 to 6, the main function is declared. Line 4 is the function header, which consists of the return type (in in this case int), this function, and the name of the function, as well as the parentheses in which the function's parameters are declared.
int — integer data type
Between the curly braces is the main program code, also called the body of the function. This is the simplest program structure. This structure written in Microsoft Visual Studio. All of the above remains true for other compilers, except for line 2. The “stdafx.h” container does not exist anywhere except MVS.
Program structure for C++ Builder.
When you create a console application, the New Project Wizard automatically generates the following code:
//preprocessor directive automatically included by the project creation wizard #include
We see that the function has a data type of int. This means that upon completion, the function will return some kind of integer value, in our case 0. Integer because int is a data type for integers, such as 4, 5, 6, 456, 233, etc.
The main thing to remember is that if the return data type of the main function is int or anything other than void, then you should write a line like this: return<возвращаемое значение>;
In line 2, the vcl.h library is included - it is automatically included by the application creation wizard, so you should not delete it, otherwise the project will not work.
In general, the wizard automatically creates a program structure that is slightly different from those we have considered, but the essence remains the same.
For example:
Int main(int argc, char* argv) ( return 0; )
This example structure is generated by the wizard in MVS2010. This main is a little different. We’ll look at it in more detail later, but I’ll say that this main looks like this because it was originally designed to support Unicode.
Unicode is a character encoding standard that allows characters to be represented in almost all written languages. We'll talk more about Unicode later.
There are different versions main , but there’s nothing wrong with that, since main was the main function and remains so, so everything said above remains relevant.
An example of the structure of an MVS program with connected libraries.
#include "stdafx.h" #include
The name of the connected libraries is written inside the greater and less than symbols. Header files and the name of the included libraries are synonyms.
Syntax for including header files:
#include<имя заголовочного файла>
Older header files are included like this (this style of connecting libraries is inherited from the C programming language):
#include<имя заголовочного файла.h>
The difference is that the name is followed by the extension .h .
The C++ programming language is case sensitive. For example:
Return 0; – not correct, there will be a compilation error.
return 0; - Right!!!
This article examines the structures of C++ programs in environments such as MVS and Borland. And as you have already noticed, these structures are almost the same. Therefore, this article is relevant for any IDE. If you have not yet decided on the choice of IDE, read.