0% found this document useful (0 votes)
15 views

C Programming 3

it is an notes for c ++ programing basics

Uploaded by

anshukiran.s30
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C Programming 3

it is an notes for c ++ programing basics

Uploaded by

anshukiran.s30
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Pointers

A pointer is variable that store address of another variable as its value .These variable could be any type
of char , int , functions, array, or other variable
The pointer sizes depend on their architecture. But, keep in mind that the size of a pointer in the 32-bit
architecture is 2 bytes

Syntax of Pointers in C

data_type * pointer_variable_name;

Declaration of a pointer
The asterisk (*)is used to declare a pointer

The dereference operator * returns the value stored at the memory address pointed to by the
pointer

the asterisk * is used for two distinct purposes in C:

 Declaring a pointer
 Dereferencing a pointer

Initialization of a pointer
&(ampersand) operator used to get the variable address in the program Pointer initialization is done
with the following syntax.
pointer = &variable;

simple program
#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the address
printf("Value stored in a variable p is:%d\n",*p); //accessing the value
return 0;
}
Types of Pointers

Null Pointer
We can create a null pointer by assigning null value during the pointer declaration.
This method is useful when you do not have any address assigned to the pointer. A
null pointer always contains value 0.
#include <stdio.h>
int main()
{
int *p = NULL; //null pointer
printf(“The value inside variable p is:\n%x”,p);
return 0;
}

Void Pointer
In C programming, a void pointer is also called as a generic pointer. It does not
have any standard data type. A void pointer is created by using the keyword void. It
can be used to store an address of any variable.
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%d\n",sizeof(p));
return 0;
}

Other types of pointers in ‘c’ are as follows:

 Wild pointer
 Dangling pointer
 Complex pointer
 Near pointer
 Far pointer
 Huge pointer
Direct and Indirect Access Pointers
In C, there are two equivalent ways to access and manipulate a variable content

 Direct access: we use directly the variable name


 Indirect access: we use a pointer to the variable

#include <stdio.h>
/* Declare and initialize an int variable */
int var = 1;

/* Declare a pointer to int */


int *ptr;
int main( void )
{

/* Initialize ptr to point to var */


ptr = &var;

/* Access var directly and indirectly */


printf("\nDirect access, var = %d", var);
printf("\nIndirect access, var = %d", *ptr);

/* Display the address of var two ways */


printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);

/*change the content of var through the pointer*/


*ptr=48;
printf("\nIndirect access, var = %d", *ptr);

return 0;}

Pointer to an array

Pointers make it easy to access each array element.

#include <stdio.h>
int main()
{
int a[5]={1,2,3,4,5}; //array initialization
int *p; //pointer declaration
/*the ptr points to the first element of the array*/

p=a; /*We can also type simply ptr==&a[0] */

printf("Printing the array elements using pointer\n");


for(int i=0;i<5;i++) //loop for traversing array elements
{
printf("\n%x",*p); //printing array elements
p++; //incrementing to the next element, you can also write p=p+1
}
return 0;
}

Pointer to a structure
#include <stdio.h>
#include <string.h>
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student s;
struct student *ptr;

/* assign values to the structure */


strcpy(s.name, "John");
s.age = 32;
s.score = 85.5;

/* make ptr point to the structure */


ptr = &s;

/* access structure members using -> operator */


printf("Name: %s\n", ptr->name);
printf("Age: %d\n", ptr->age);
printf("Score: %.2f\n", ptr->score);
return 0;
}

Pointer to a String

#include <stdio.h>

int main() {
char *str = "Hello, world!";
printf("%s\n", str);

return 0;

Advantages of Pointers in C
 Pointers are useful for accessing memory locations.
 Pointers provide an efficient way for accessing the elements of an array
structure.
 Pointers are used for dynamic memory allocation as well as deallocation.
 Pointers are used to form complex data structures such as linked list, graph,
tree, etc.

Disadvantages of Pointers in C
 Pointers are a little complex to understand.
 Pointers can lead to various errors such as segmentation faults or can access
a memory location which is not required at all.
 If an incorrect value is provided to a pointer, it may cause memory
corruption.
 Pointers are also responsible for memory leakage.
 Pointers are comparatively slower than that of the variables.
 Programmers find it very difficult to work with the pointers; therefore it is
programmer’s responsibility to manipulate a pointer carefully

Function

A function is a block of code that performs a specific task.

In this way, if we break a complex program into functions, where each function performs a much
simpler task, the program will become simple to code and will improve readability. functions can
be reused again and again throughout the program, whenever required. This also helps in
reducing repetitive codes in our program.

Benefits of using FUNCTIONS:

 C functions are used to avoid rewriting same logic/code again and again in a program.
 There is no limit in calling C functions to make use of same functionality wherever required.
 We can call functions any number of times in a program and from any place in a program.
 A large C program can easily be tracked when it is divided into functions.
 The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs
functions can be classified into two categories,
1. Library functions

2. User-defined functions

Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use
these functions. These are already declared and defined in C libraries.

A User-defined functions on the other hand, are those functions which are defined by the user
at the time of writing program. These functions are made for code reusability and for saving
time and space.

Function Declaration

The function declaration tells the compiler about function name, the data type of the
return value and parameters. The function declaration is also called a function
prototype. The function declaration is performed before the main function or inside the
main function or any other function.It's also called as Function Prototyping. Function
declaration consists of 4 parts.
 Return type: This specifies the data type of the value that the function returns.
 Function name: This is a unique identifier for the function.
 Parameters: These are the values that are passed to the function when it is called. Each
parameter consists of a data type and a parameter name.
 Function body: This is the block of code that defines the actions that the function will
perform
Function declaration syntax

return_type, function_name (parameter_data_type p1, parameter_data_type p2, ..);

Defining function or function definition

Defining a function means specifying the body inside the function. This will be the code
that will be executed every time the function is called .

The function definition provides the actual code of that function. The function definition is
also known as the body of the function. The function body contains the declarations and the
statements(algorithm) necessary for performing the required task the actual instructions to
be performed by a function are written in function definition. The body is enclosed within
curly braces { ... } and consists of three parts.

 local variable declaration(if required).

 function statements to perform the task inside the function.


 a return statement to return the result evaluated by the function(if return type
is void, then no return statement is required)

The function definition is performed before the main function or after the main function.

There are 3 aspects in each C function. They are,

 Function declaration or prototype – This informs compiler about the function name, function parameters
and return value’s data type.
 Function definition – This contains all the statements to be executed.
 Function call – This calls the actual function

Calling a function

When a function is called, control of the program gets transferred to the function.

A function call is the act of invoking a function in order to execute its code. It involves
passing arguments to the function and receiving a return value from it.

In C, a function call is made by using the function name followed by a set of parentheses
that contain the arguments to be passed to the function. The arguments are separated by
commas.

Function calling in C is the process of executing the code inside a function by using its
name. It's a way of telling the program to run a specific block of code when it's needed.
Think of a function as a mini-program within your main program. When you want to use
the mini-program, you "call" it by writing the function name followed by a set of
parentheses. Inside the parentheses, you can pass in any arguments that the function
needs to do its job.

Syntax for calling function in c

return_type result = function_name(argument_list);


There are two ways that a C function can be called from a program. They are,

1. Call by value
2. Call by reference

CALL BY VALUE:
When passing arguments to a function by value, a copy of the actual argument is created and passed to the function. This means
that any changes made to the parameter inside the function have no effect on the actual argument outside the function. In call by
value, only the value of the variable is passed to the function.

 In call by value method, the value of the variable is passed to the function as parameter.
 The value of the actual parameter can not be modified by formal parameter.
 Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.

CALL BY REFERENCE:
When passing arguments to a function by reference, a reference or pointer to the actual argument is passed to the function

 In call by reference method, the address of the variable is passed to the function as parameter.
 The value of the actual parameter can be modified by formal parameter.
 Same memory is used for both actual and formal parameters since only address is used by both parameters.

Passing Arguments to a function

functions can accept parameters, also known as arguments. These arguments are passed to the
function when it is called, and the function can use the values of these arguments to perform its
operations.

Arguments are the values specified during the function call, for which the formal parameters are
declared while defining the function.
Note:

Formal parameters and actual parameters are terms used in computer programming to describe the
parameters used in a function.

Formal parameters are the parameters listed in the function declaration or definition. They are
placeholders for the values that will be passed to the function when it is called.

Actual parameters, on the other hand, are the values passed to the function when it is called
 Actual parameter – This is the argument which is used in function call.
 Formal parameter – This is the argument which is used in function definition

Returning a value from function

A Function can return a value to the calling code using the return statement. The return type of
a function is specified in the function declaration and determines the type of value that the
function will return

#include <stdio.h>

int square(int num) {


int result = num * num;
return result;
}

int main() {
int x = 10;
int y = square(x);
printf("The square of %d is %d\n", x, y);
return 0;
}

Library Functions
The library functions are built-in functions. In C programming language, the standard functions

are declared in header files and defined in .dll files. In simple words, the standard functions can

be defined as "the ready made functions defined by the system to make coding more easy".

The standard functions are also called as standard functions or pre-defined functions.

when we use standard functions, we must include the respective header file
using #include statement. For example, the function printf() is defined in header
file stdio.h (Standard Input Output header file). When we use printf() in our
program, we must include stdio.h header file using #include<stdio.h> statement.
Header
File Purpose Example

stdio.h Provides functions to perform standard I/O operations printf(), scanf()

conio.h Provides functions to perform console I/O operations clrscr(), getch()

math.h Provides functions to perform mathematical operations sqrt(), pow()

string.h Provides functions to handle string data values strlen(), strcpy()

stdlib.h Provides functions to perform general functions/td> calloc(), malloc()

time.h Provides functions to perform operations on time and date time(), localtime()

ctype.h Provides functions to perform - testing and mapping of isalpha(), islower()


character data values

setjmp.h Provides functions that are used in function calls setjump(), longjump()

signal.h Provides functions to handle signals during program signal(), raise()


execution

assert.h Provides Macro that is used to verify assumptions made by assert()


the program

locale.h Defines the location specific settings such as date formats setlocale()
and currency symbols

stdarg.h Used to get the arguments in a function if the arguments are va_start(), va_end(), va_arg()
not specified by the function

errno.h Provides macros to handle the system calls Error, errno

graphics.h Provides functions to draw graphics. circle(), rectangle()

float.h Provides constants related to floating point data values

stddef.h Defines various variable types

limits.h Defines the maximum and minimum values of various variable


types like char, int and long
C Programming Language provides the following header files with standard
functions.

Recursive Functions in C
A function called by itself in order to solve a problem. this technique is known as recursion

#include <stdio.h>

int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("The factorial of %d is %d\n", num, factorial(num));
return 0;
}

Preprocessor
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation.

The C preprocessor is a macro processor that is used automatically by the C compiler to


transform your program before actual compilation. It is called a macro processor because it
allows you to define macros, which are brief abbreviations for longer constructs.

The C preprocessor provides four separate facilities that you can use as you see fit:

 Inclusion of header files. These are files of declarations that can be substituted into your program.
 Macro expansion. You can define macros, which are abbreviations for arbitrary fragments of C
code, and then the C preprocessor will replace the macros with their definitions throughout the
program.
Macro

Macro substitution has a name and replacement text, defined with #define directive. The preprocessor
simply replaces the name of macro with replacement text from the place where the macro is defined in the
source code.

include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)

int main() {
float radius, area;

printf("Enter the radius: ");


scanf("%f", &radius);
area = circleArea(radius);
printf("Area = %.2f", area);

return 0;
}

C programming language, there are some pre-defined macros and they are as follows...

1. __ DATE __ : The current date as characters in "MMM DD YYYY" format.


2. __ TIME __ : The current time as characters in "HH : MM : SS" format.
3. __ FILE __ : This contains the current file name.
4. __ LINE __ : This contains the current line number.
5. __ STDC __ : Defines 1 when compiler compiles with ANSI Standards.

C – Command line arguments


File
Input output

Control statements

Loops statement

Break statement

Decision making

You might also like