SlideShare a Scribd company logo
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 – Preprocessordirectives
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.
Preprocessor Syntax/Description
Macro
Syntax: #define
This macro defines constant value and can be any
of the basic data types.
Header file
inclusion
Syntax: #include <file_name>
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. First region – This is the memory region which holds the executable code of the program.
2. 2nd
region – In this memory region, global variables are stored.
3. 3rd
region – stack
4. 4th region – heap
DO YOU KNOW DIFFERENCE BETWEEN STACK & HEAP MEMORY IN C LANGUAGE?
Stack Heap
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 is a memory region
which is used by dynamic
memory allocation
functions at run time.
CPU’s current state is saved in stack
memory
Linked list is an example
which uses heap memory.
DO YOU KNOW DIFFERENCE BETWEEN COMPILERS VS INTERPRETERS IN C LANGUAGE?
Compilers Interpreters
Compiler reads the entire source
code of the program and converts
it into binary code. This process
Interpreter reads the program
source code one line at a time and
executing that line. This process is
is called compilation.
Binary code is also referred as
machine code, executable, and
object code.
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. Source program is converted into executable code through different processes like precompilation, compilation,
assembling and linking.
2. Local variables uses stack memory.
3. Dynamic memory allocation functions use the heap memory.
EXAMPLE PROGRAM FOR #DEFINE,#INCLUDE PREPROCESSORS INC LANGUAGE:
 #define – This macro defines constant value and can be any of the basic data types.
 #include <file_name> – The source code of the file “file_name” is included in the main C program where “#include
<file_name>” is mentioned.
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '?'
void main()
{
printf("value of height : %d n", height );
printf("value of number : %f n", number );
printf("value of letter : %c n", letter );
printf("value of letter_sequence : %s n", letter_sequence);
15
16
17
printf("value of backslash_char : %c n", backslash_char);
}
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:
 “#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.
C
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " 
"this C filen");
#else
printf("RAJU is not definedn");
#endif
return 0;
}
OUTPUT:
RAJU is defined. So, this line will be added in this C file
B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN 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.
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " 
"define heren");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);
#endif
return 0;
}
OUTPUT:
SELVA is not defined. So, now we are going to define here
C) EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN 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.
C
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " 
"a = 100n");
#else
printf("This line will be added in this C file since " 
"a is not equal to 100n");
#endif
return 0;
}
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
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#define height 100
void main()
{
printf("First definedvalue for height : %dn",height);
#undef height // undefining variable
#define height 600 // 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
{
printf ( "n Now we are in main function" ) ;
return 0;
}
void function1( )
{
printf("nFunction1 is called before main function call");
}
void function2( )
{
printf ( "nFunction2 is called just before end of " 
"main function" ) ;"
24 }
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
<function_name_1>
This directive executes function named
“function_name_1” before
#Pragma exit
<function_name_2>
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 <stdio.h>
/* 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 : %dn", 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. Call Type & Description
1 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 i, j, k;
char c, ch;
float f, salary;
double 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; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x 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 been defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d n", c);
f = 70.0/3.0;
printf("value of f : %f n", f);
return 0;
}
When the above code is compiled and executed, it produces the following
result −
value of c : 30
value of f : 23.333334
The same concept applies on function declaration where you provide a
function name at the time of its declaration and its actual definition can
be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
Lvalues and Rvalues in C
There are two kinds of expressions in C −
 lvalue − Expressions that refer to a memory location are called "lvalue" expressions.
An lvalue may appear as either the left-hand or right-hand side of an assignment.
 rvalue − The term rvalue refers to a data value that is stored at some address in
memory. An rvalue is an expression that cannot have a value assigned to it which
means an rvalue may appear on the right-hand side but not on the left-hand side of
an assignment.
Variables are lvalues and so they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and so they may not be
assigned and cannot appear on the left-hand side. Take a look at the
following valid and invalid statements −
int g = 20; // valid statement
10 = 20; // invalid statement; would generate compile -time error

More Related Content

What's hot

Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
Mahantesh Devoor
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21myrajendra
 
Features of c language 1
Features of c language 1Features of c language 1
Features of c language 1
srmohan06
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
Rumman Ansari
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
sangrampatil81
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
 
C language ppt
C language pptC language ppt
C language ppt
Ğäùråv Júñêjå
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
Muthuselvam RS
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
Leela Koneru
 
Java Tokens
Java  TokensJava  Tokens
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
C Language
C LanguageC Language
C Language
Aakash Singh
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 

What's hot (20)

Functions in C
Functions in CFunctions in C
Functions in C
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 
Data types
Data typesData types
Data types
 
Features of c language 1
Features of c language 1Features of c language 1
Features of c language 1
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
C language ppt
C language pptC language ppt
C language ppt
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
C Language
C LanguageC Language
C Language
 
Function in c
Function in cFunction in c
Function in c
 

Similar to Basic structure of c programming

Preprocessor
PreprocessorPreprocessor
Preprocessor
lalithambiga kamaraj
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
REHAN IJAZ
 
lecture1 pf.pptx
lecture1 pf.pptxlecture1 pf.pptx
lecture1 pf.pptx
MalikMFalakShairUnkn
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro header
hasan Mohammad
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
Sivakumar R D .
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
tanmaymodi4
 
Preprocessor directives in c laguage
Preprocessor directives in c laguagePreprocessor directives in c laguage
Preprocessor directives in c laguage
Tanmay Modi
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeks
AashutoshChhedavi
 
C structure
C structureC structure
C structure
ankush9927
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
Sowri Rajan
 
C programming course material
C programming course materialC programming course material
C programming course material
Ranjitha Murthy
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)indrasir
 
Basics of c Nisarg Patel
Basics of c Nisarg PatelBasics of c Nisarg Patel
Basics of c Nisarg Patel
TechNGyan
 
Chapter3
Chapter3Chapter3
Chapter3
Kamran
 
C programming
C programmingC programming
C programming
PralhadKhanal1
 
C++ Constructs.pptx
C++ Constructs.pptxC++ Constructs.pptx
C++ Constructs.pptx
LakshyaChauhan21
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
kinish kumar
 

Similar to Basic structure of c programming (20)

Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
 
ANSI C Macros
ANSI C MacrosANSI C Macros
ANSI C Macros
 
lecture1 pf.pptx
lecture1 pf.pptxlecture1 pf.pptx
lecture1 pf.pptx
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro header
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
 
Preprocessor directives in c laguage
Preprocessor directives in c laguagePreprocessor directives in c laguage
Preprocessor directives in c laguage
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeks
 
C structure
C structureC structure
C structure
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
Unit 5 quesn b ans5
Unit 5 quesn b ans5Unit 5 quesn b ans5
Unit 5 quesn b ans5
 
C programming course material
C programming course materialC programming course material
C programming course material
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
Basics of c Nisarg Patel
Basics of c Nisarg PatelBasics of c Nisarg Patel
Basics of c Nisarg Patel
 
Chapter3
Chapter3Chapter3
Chapter3
 
C programming
C programmingC programming
C programming
 
C++ Constructs.pptx
C++ Constructs.pptxC++ Constructs.pptx
C++ Constructs.pptx
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 

More from TejaswiB4

Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)
TejaswiB4
 
Chapter 4(1)
Chapter 4(1)Chapter 4(1)
Chapter 4(1)
TejaswiB4
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
TejaswiB4
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)
TejaswiB4
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)
TejaswiB4
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 

More from TejaswiB4 (6)

Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)
 
Chapter 4(1)
Chapter 4(1)Chapter 4(1)
Chapter 4(1)
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 

Recently uploaded

block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 

Recently uploaded (20)

block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 

Basic structure of c programming

  • 1. 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
  • 2. 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 – Preprocessordirectives 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. Preprocessor Syntax/Description Macro Syntax: #define This macro defines constant value and can be any of the basic data types. Header file inclusion Syntax: #include <file_name> 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.
  • 3. There are 4 regions of memory which are created by a compiled C program. They are, 1. First region – This is the memory region which holds the executable code of the program. 2. 2nd region – In this memory region, global variables are stored. 3. 3rd region – stack 4. 4th region – heap DO YOU KNOW DIFFERENCE BETWEEN STACK & HEAP MEMORY IN C LANGUAGE? Stack Heap 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 is a memory region which is used by dynamic memory allocation functions at run time. CPU’s current state is saved in stack memory Linked list is an example which uses heap memory. DO YOU KNOW DIFFERENCE BETWEEN COMPILERS VS INTERPRETERS IN C LANGUAGE? Compilers Interpreters Compiler reads the entire source code of the program and converts it into binary code. This process Interpreter reads the program source code one line at a time and executing that line. This process is
  • 4. is called compilation. Binary code is also referred as machine code, executable, and object code. 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. Source program is converted into executable code through different processes like precompilation, compilation, assembling and linking. 2. Local variables uses stack memory. 3. Dynamic memory allocation functions use the heap memory. EXAMPLE PROGRAM FOR #DEFINE,#INCLUDE PREPROCESSORS INC LANGUAGE:  #define – This macro defines constant value and can be any of the basic data types.  #include <file_name> – The source code of the file “file_name” is included in the main C program where “#include <file_name>” is mentioned. C 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <stdio.h> #define height 100 #define number 3.14 #define letter 'A' #define letter_sequence "ABC" #define backslash_char '?' void main() { printf("value of height : %d n", height ); printf("value of number : %f n", number ); printf("value of letter : %c n", letter ); printf("value of letter_sequence : %s n", letter_sequence);
  • 5. 15 16 17 printf("value of backslash_char : %c n", backslash_char); } 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:  “#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. C 1 2 3 4 5 6 7 8 9 10 11 12 13 #include <stdio.h> #define RAJU 100 int main() { #ifdef RAJU printf("RAJU is defined. So, this line will be added in " "this C filen"); #else printf("RAJU is not definedn"); #endif return 0; } OUTPUT: RAJU is defined. So, this line will be added in this C file
  • 6. B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN 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. C 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <stdio.h> #define RAJU 100 int main() { #ifndef SELVA { printf("SELVA is not defined. So, now we are going to " "define heren"); #define SELVA 300 } #else printf("SELVA is already defined in the program”); #endif return 0; } OUTPUT: SELVA is not defined. So, now we are going to define here C) EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN 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. C
  • 7. 1 2 3 4 5 6 7 8 9 10 11 12 13 #include <stdio.h> #define a 100 int main() { #if (a==100) printf("This line will be added in this C file since " "a = 100n"); #else printf("This line will be added in this C file since " "a is not equal to 100n"); #endif return 0; } 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 2 3 4 5 6 7 8 9 10 #include <stdio.h> #define height 100 void main() { printf("First definedvalue for height : %dn",height); #undef height // undefining variable #define height 600 // redefining the same for new value printf("value of height after undef & redefine:%d",height); }
  • 8. 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include <stdio.h> void function1( ); void function2( ); #pragma startup function1 #pragma exit function2 int main( ) { printf ( "n Now we are in main function" ) ; return 0; } void function1( ) { printf("nFunction1 is called before main function call"); } void function2( ) { printf ( "nFunction2 is called just before end of " "main function" ) ;"
  • 9. 24 } 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 <function_name_1> This directive executes function named “function_name_1” before #Pragma exit <function_name_2> 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
  • 10. 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;
  • 11. 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.
  • 12. 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 <stdio.h> /* 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 : %dn", 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; }
  • 13. 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. Call Type & Description 1 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.
  • 14. 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 i, j, k; char c, ch; float f, salary; double 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.
  • 15. 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; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = 'x'; // the variable x 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 been defined and initialized inside the main function − #include <stdio.h> // Variable declaration: extern int a, b; extern int c; extern float f; int main () {
  • 16. /* variable definition: */ int a, b; int c; float f; /* actual initialization */ a = 10; b = 20; c = a + b; printf("value of c : %d n", c); f = 70.0/3.0; printf("value of f : %f n", f); return 0; } When the above code is compiled and executed, it produces the following result − value of c : 30 value of f : 23.333334 The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example − // function declaration int func(); int main() { // function call int i = func(); } // function definition int func() { return 0; }
  • 17. Lvalues and Rvalues in C There are two kinds of expressions in C −  lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.  rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements − int g = 20; // valid statement 10 = 20; // invalid statement; would generate compile -time error