Basic structure of C programming PDF

Title Basic structure of C programming
Author TEJASWI B
Course Programming For Problem Solving
Institution Vignan's Foundation for Science, Technology and Research
Pages 18
File Size 669 KB
File Type PDF
Total Downloads 60
Total Views 176

Summary

Basic structure of C programming. Theory and examples....


Description

Basic structure of C programming: To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are illustrated below.

1. Documentation section: The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. 2. Link section: The link section provides instructions to the compiler to link functions from the system library such as using the #include directive. 3. Definition section: The definition section defines all symbolic constants such using the #define directive . 4. Global declaration section: There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions. 5. main () function section: Every C program must have one main function section. This section contains two parts; declaration part and executable part

1. Declaration part: The declaration part declares all the variables used in the executable part. 2. Executable part: There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. 6. Subprogram section: If the program is a multi-function program then the subprogram section contains all the user-defined functions that are called in the main () function. User-defined functions are generally placed immediately after the main () function, although they may appear in any order. All section, except the main () function section may be absent when they are not required.

C – Preprocessor directives PREV

NEXT

C PREPROCESSOR DIRECTIVES: Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This process is called preprocessing.  Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol. Below is the list of preprocessor directives that C programming language offers. 

Preprocess or

Syntax/Description

Macro

Syntax: #define This macro defines constant value and can be any of the basic data types.

Header file inclusion

Syntax: #include The source code of the file “file_name” is included in the main program at the specified place.

Conditional compilation

Syntax: #ifdef, #endif, #if, #else, #ifndef Set of commands are included or excluded in source program before compilation with respect to the condition.

Other directives

Syntax: #undef, #pragma #undef is used to undefine a defined

macro variable. #Pragma is used to call a function before and after main function in a C program. A program in C language involves into different processes. Below diagram will help you to understand all the processes that a C program comes across.

There are 4 regions of memory which are created by a compiled C program. They are, 1. 2. 3. 4.

First region – This is the memory region which holds the executable code of the program. 2nd region – In this memory region, global variables are stored. 3rd region – stack 4th region – heap

DO YOU KNOW DIFFERENCE BETWEEN STACK & HEAP MEMORY IN C LANGUAGE?

Stack Stack is a memory region where “local variables”, “return addresses of function calls” and “arguments to functions” are hold while C program is executed.

Heap

Heap is a memory region which is used by dynamic memory allocation functions at run time.

CPU’s current state is saved in stack memory DO YOU KNOW LANGUAGE?

DIFFERENCE

BETWEEN

Compilers Compiler reads the entire source code of the program and converts it into binary code. This process is called compilation.

Linked list is an example which uses heap memory. COMPILERS

VS INTERPRETERS

IN

C

Interpreters

Binary code is also referred as machine code, executable, and object code.

Interpreter reads the program source code one line at a time and executing that line. This process is called interpretation.

Program speed is fast.

Program speed is slow.

One time execution. Example: C, C++

Interpretation occurs at every line of the program. Example: BASIC

KEY POINTS TO REMEMBER: 1. 2. 3.

Source program is converted into executable code through different processes like precompilation, compilation, assembling and linking. Local variables uses stack memory. Dynamic memory allocation functions use the heap memory.

EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C LANGUAGE:  

#define – This macro defines constant value and can be any of the basic data types. #include – The source code of the file “file_name” is included in the main C program where “#include ” is mentioned.

C

1 #include 2 3 #define height 100

4 5 6 #define number 3.14 7 #define letter 'A' 8 #define letter_sequence "ABC" 9 #define backslash_char '\?' 1 0 void main() 1 1 { 1 2

printf("value of height

: %d \n", height );

printf("value of number : %f \n", number ); 1 3

printf("value of letter : %c \n", letter ); printf("value of letter_sequence : %s \n", letter_sequence);

1 4

printf("value of backslash_char : %c \n", backslash_char); 1 5 1 } 6 1 7

OUTPUT:

value of height : 100 value of number : 3.140000 value of letter : A value of letter_sequence : ABC value of backslash_char : ? EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION DIRECTIVES: A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:   C

“#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause statements are included in source file. Otherwise, “else” clause statements are included in source file for compilation and execution.

1 2 #include 3 #define RAJU 100 4 5 int main() 6 { 7

#ifdef RAJU

8

printf("RAJU is defined. So, this line will be added in " \

9

"this C file\n");

1 0

#else printf("RAJU is not defined\n");

1 1

#endif

1 2

return 0; }

1 3

OUTPUT:

RAJU is defined. So, this line will be added in this C file B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:   C

#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If” clause statements are included in source file. Otherwise, else clause statements are included in source file for compilation and execution.

1 #include 2 #define RAJU 100 3 int main() 4 {

5 6 7

#ifndef SELVA

8

{

9

printf("SELVA is not defined. So, now we are going to " \

1 0

"define here\n"); #define SELVA 300

1 1

}

1 2

#else printf("SELVA is already defined in the program”);

1 3 #endif

1 4

return 0; 1 5 1 } 6 1 7

OUTPUT:

SELVA is not defined. So, now we are going to define here C) EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:   C

“If” clause statement is included in source file if given condition is true. Otherwise, else clause statement is included in source file for compilation and execution.

1 #include 2 #define a 100 3 int main() 4 { 5

#if (a==100)

6

printf("This line will be added in this C file since " \

7 8

"a \= 100\n");

9

#else

1 0

printf("This line will be added in this C file since " \ "a is not equal to 100\n");

1 1

#endif return 0;

1 2 } 1 3

OUTPUT:

This line will be added in this C file since a = 100 EXAMPLE PROGRAM FOR UNDEF IN C LANGUAGE: This directive undefines existing macro in the program. C

1

#include

2 3 4 5

#define height 100 void main() {

6 7 8 9 1 } 0

printf("First defined value for height #undef height #define height 600

: %d\n",height);

// undefining variable // redefining the same for new value

printf("value of height after undef \& redefine:%d",height);

OUTPUT:

First defined value for height : 100 value of height after undef & redefine : 600 EXAMPLE PROGRAM FOR PRAGMA IN C LANGUAGE: Pragma is used to call a function before and after main function in a C program. C

1 #include 2 3 void function1( ); 4 void function2( ); 5 6 #pragma startup function1 7 #pragma exit function2 8 9 int main( ) 1 { 0 printf ( "\n Now we are in main function" ) ; 1 1

return 0;

1 } 2 1 3 void function1( ) 1 { 4

printf("\nFunction1 is called before main function call");

1 5 } 1 6

void function2( )

1 { 7 1 8

printf ( "\nFunction2 is called just before end of " \

1 9 2 0 2 1

"main function" ) ;"

2 } 2 2 3 2 4

OUTPUT:

Function1 is called before main function call Now we are in main function Function2 is called just before end of main function MORE ON PRAGMA DIRECTIVE IN C LANGUAGE:

Pragma command

Description

#Pragma startup

This directive executes function named “function_name_1” before

#Pragma exit

This directive executes function named “function_name_2” just before termination of the program.

#pragma warn – rvl

If function doesn’t return a value, then warnings are suppressed by this directive while compiling.

#pragma warn – par

If function doesn’t use passed function parameter , then warnings are suppressed

#pragma warn – rch

If a non reachable code is written inside a program, such warnings are suppressed by this directive.

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function The general form of a function definition in C programming language is as follows − return_type function_name( parameter list ) { body of the function }

A function definition in C programming consists of a function header and afunction body. Here are all the parts of a function − 

Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.



Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.



Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.



Function Body − The function body contains a collection of statements that define what the function does.

Example Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two − /* function returning the max between two numbers */ int max(int num1, int num2) {

/* local variable declaration */ int result;

if (num1 > num2) result = num1; else result = num2;

return result; }

Function Declarations A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts − return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows − int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration − int max(int, int);

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program. To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example − #include

/* function declaration */ int max(int num1, int num2);

int main () {

/* local variable definition */ int a = 100; int b = 200; int ret;

/* calling a function to get max value */ ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0; }

/* function returning the max between two numbers */ int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2) result = num1; else result = num2;

return result; }

We have kept max() along with main() and compiled the source code. While running the final executable, it would produce the following result − Max value is : 200

Function Arguments If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways in which arguments can be passed to a function − S.N .

1

Call Type & Description

Call by value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

2

Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function. A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types − Type

Description

char

Typically a single octet(one byte). This is an integer type.

int

The most natural size of integer for the machine.

float

A single-precision floating point value.

double

A double-precision floating point value.

void

Represents the absence of type.

C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types.

Variable Definition in C A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − type variable_list;

Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist

of one or more identifier names separated by commas. Some valid declarations are shown here − int char float double

i, j, k; c, ch; f, salary; d;

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value;

Some examples are − extern int d = 3, f = 5; int d = 3, f = 5; byte z = 22; char x = 'x';

// // // //

declaration of definition and definition and the variable x

d and f. initializing d and f. initializes z. has the value 'x'.

For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined.

Variable Declaration in C A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program. A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.

Example Try the following example, where variables have been declared at the top, but they have...


Similar Free PDFs