c type cast
TRANSCRIPT
-
7/28/2019 C type cast
1/23
C type casting
Prev Next
CTypecasting concept is used to modify a variable from one date type to another data type. New data type should be mentioned before the variable in brackets which to be type casted.
C Type casting Example program:
In the below program, 7/5 alone will produce integer value. So, type cast is done before division to retain float result.
C
// Structure using typedef:
3
4
1
23
4
5
67
#include
int main (){
float x;
x = (float) 7/5;
printf("%f",x);
Output:
1.400000
It is best practice to convert lower data type to higher data type to avoid data loss. Data will be truncated when higher data type is converted to lower. For example, if float is converted to int, data which is present after decimal
point will be lost.
Inbuilt typecast functions:
There are many inbuilt typecast functions available in C language which performs data type conversion from one type to another. They are
given in below table. Click on each function name to display an example program.S.no Function Description
1 atof Converts string to float
2 atoi Converts string to int
3 atol Converts string to long
4 itoa Converts int to string
5 ltoa Converts long to string
http://fresh2refresh.com/c/c-union/http://fresh2refresh.com/c/c-preprocessor-directives/http://fresh2refresh.com/c/c-preprocessor-directives/http://fresh2refresh.com/c/c-preprocessor-directives/http://fresh2refresh.com/c/c-union/http://fresh2refresh.com/c/c-union/http://fresh2refresh.com/c/c-object-exe-file-creation/ -
7/28/2019 C type cast
2/23
Example program for atof():
It converts string to float data type.
C
#include
#include
int main()
1
2
3
4
5
67
8
9
10
#include
#include
int main()
{
char a[10] = "3.14";float pi = atof(a);
printf("Value of pi = %f\n", pi);
return 0;
}Output:
Value of pi = 3.140000
Example program for atoi():
It converts string to int data type.
C
5
6
7
1
2
3
45
6
7
89
#include
#include
int main(){
char a[10] = "100";
int value = atoi(a);
printf("Value = %d\n", value);return 0;
-
7/28/2019 C type cast
3/23
10 }Output:
Value = 100
Example program for atol():
It converts string to long data type.
C
#include
#include
#include
1
2
3
4
5
67
8
9
10
#include
#include
int main()
{
char a[20] = "100000000000";long value = atol(a);
printf("Value = %ld\n", value);
return 0;
}
Output:
Value = 100000000000
Example program for itoa():
It converts int to string data type.
C
1
23456
789
1011
121314
1516
#include
#include #include
int main(){
int a=54325;char buffer[20];itoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);
itoa(a,buffer,10); // here 10 means decimalprintf("Decimal value = %s\n", buffer);
itoa(a,buffer,16); // here 16 means Hexadecimalprintf("Hexadecimal value = %s\n", buffer);
-
7/28/2019 C type cast
4/23
1718
return 0;}
Output:
Binary value = 1101010000110101
Decimal value = 54325
Hexadecimal value = D435Example program for ltoa():
It converts long to string data type.
C
1
2
34
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include
#include
#include
int main()
{
long a=10000000;
char buffer[50];
ltoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);
ltoa(a,buffer,10); // here 10 means decimal
printf("Decimal value = %s\n", buffer);
ltoa(a,buffer,16); // here 16 means Hexadecimal
printf("Hexadecimal value = %s\n", buffer);
return 0;
}
Output:
Binary value = 100110001001011010000000
Decimal value = 10000000
Hexadecimal value = 989680
C typedef
Prev Next
C- Typedef : It is a keyword that is used to give a new symbolic name for the existing name in a C program. This is same like defining alias for the commands. Consider the below structure
struct student
{
int mark [2];
char name [10];
float average;
};
Variable for the above structure can be declared in two ways.1st way :
struct student record; // for normal variable
http://fresh2refresh.com/c/c-structures/http://fresh2refresh.com/c/c-union/http://fresh2refresh.com/c/c-union/http://fresh2refresh.com/c/c-union/http://fresh2refresh.com/c/c-structures/http://fresh2refresh.com/c/c-structures/http://fresh2refresh.com/c/c-object-exe-file-creation/ -
7/28/2019 C type cast
5/23
struct student *record; // for pointer variable
2nd way :
typedef struct student status;
When we use typedef keyword before struct like above, after that we can simply use type definition (here it is sta tus) in the C program to declare
structure variable.
Now, structure variable declaration will be, status record. This is equal to struct student record. Type definition for struct student is status.
i.e. status = struct student
C -typedef : An alternative way for structure declaration:
typedef struct student
{
int mark [2];
char name [10];
float average;
}status;
To declare structure variable, we can use the below statements.
status record1; //record 1 is structure variable
status record2; //record 2 is structure variable
Example program for C typedef :
C
1
2
3
4
5
6
7
8
9
10
11
12
1314
15
16
17
18
19
20
21
22
23
// Structure using typedef:
#include
#include
typedef struct student
{
int id;
char name[20];
float percentage;
} status;
int main(){
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
Output:
-
7/28/2019 C type cast
6/23
Id is: 1
Name is: Raju
Percentage is: 86.500000
Typedef can be used to simplify the rea l commands as per our need.For example,
typedef long long int LLI;
In above statement, LLI is the type definition for the real C command long long int. We can use type defini tion LLI instead of using full command long long int in
a C program once it is de fined.
Another example program for C typedef:
C
1
23
4
5
6
7
8
9
10
11
12
#include
#include
int main()
{
typedef long long int LLI;
printf("Storage size for long long int data " \
"type : %ld \n", sizeof(LLI));
return 0;
}
Output:
Storage size for long long int data type : 8
C Command line arguments
Prev Next
Command line arguments in C:
main() function of a C program accepts arguments from command line or from other shell scripts by following
commands. They are,
argc argv[]
where,
argc - number of arguments in the command line including program name
argv[] - This is carrying all the arguments .
In real time application, it will happen to pass arguments to the main program itself. These arguments arepassed to the main () function while executing binary file from command line.
http://fresh2refresh.com/c/c-preprocessor-directives/http://fresh2refresh.com/c/c-variable-length-arguments/http://fresh2refresh.com/c/c-variable-length-arguments/http://fresh2refresh.com/c/c-variable-length-arguments/http://fresh2refresh.com/c/c-preprocessor-directives/http://fresh2refresh.com/c/c-object-exe-file-creation/ -
7/28/2019 C type cast
7/23
For example, when we compile a program (test.c), we get executable file in the name test. Now, we run the executable test along with 4 arguments in command line like below.
./test this is a program
Where,
argc = 5
argv[0] = test
argv[1] = this
argv[2] = is
argv[3] = a
argv[4] = program
argv[5] = NULL
Example program for argc() and argv() functions:
C
1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19
#include
#include
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf("Arguments passed through command line " \
"not equal to 5");
return 1;}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
-
7/28/2019 C type cast
8/23
20
21
return 0;
}
Output:
Program name : test
1st arg : this2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
Do you know difference between int and void data type used in functions?
S.no int void
1
int main ()
In the above statement, int means, this main
function returns a value of integer data type
to the calling function.
void main ()
In the above statement, void means, this
main function doesnt return any value to
the calling function.
2 int main () and int main (void) are same.void main () and void main (void) are
same.
3
int main (int argc, char + argv ())In the
above statement, arguments are passed to
the main function. Where,
argc no. of arguments passed.
agrv ()carries passed arguments. The
above function gets the argument from
command line and returns the integer value.
void main (int argc, char + argv ())This gets
arguments from command line. But,
doesnt return any value to calling function.
C Preprocessor directives
Prev Next
CPreprocessor directives:
Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. Thisprocess 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 language offers.
S.no Preprocessor Syntax Description
1 Macro #defineThis macro defines constant value and can be
any of the basic data types.
2Header file
inclusion#include
The source code of the file file_name is
included in the main program at the specified
place
http://fresh2refresh.com/c/c-type-casting/http://fresh2refresh.com/c/c-command-line-arguments/http://fresh2refresh.com/c/c-command-line-arguments/http://fresh2refresh.com/c/c-command-line-arguments/http://fresh2refresh.com/c/c-type-casting/http://fresh2refresh.com/c/c-type-casting/http://fresh2refresh.com/c/c-object-exe-file-creation/ -
7/28/2019 C type cast
9/23
3Conditional
compilation#ifdef, #endif, #if,
#else, #ifndef
Set of commands are included or excluded in
source program before compilation with
respect to the condition
4 Other directives # 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
process that a C program comes across.
Example program for #define, #include C preprocessors:
#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 program at the specified place
C
-
7/28/2019 C type cast
10/23
1
2
3
4
5
6
78
9
10
11
12
13
14
15
16
17
#include
#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);
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:
#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
78
9
10
11
12
13
#include
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
Output:
-
7/28/2019 C type cast
11/23
RAJU is defined. So, this line will be added in this C file
b) Example program for #ifndef and #endif:
It 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
45
6
7
8
9
10
11
12
13
14
15
16
17
#include
#define RAJU 100
int main()
{#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#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:
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
#include
#define a 100
-
7/28/2019 C type cast
12/23
3
4
5
6
7
8
910
11
12
13
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \"a is not equal to 100\n");
#endif
return 0;
}
Output:
This line will be added in this C file since a = 100
Example program for undef:
This directive undefines existing macro in the program.
C
1
2
3
4
56
7
8
9
10
#include
#define height 100
void main()
{printf("First defined value for height : %d \n", 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:
Pragma is used to call a function before and after main function in a C program
C
-
7/28/2019 C type cast
13/23
1
2
3
4
5
6
78
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include
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" ) ;"
}
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:
S.no Pragma command description
1#Pragma startup
This directive executes function named
function_name_1 before
2#Pragma exit
This directive executes function named
function_name_2 just before termination of the program
3 #pragma warnrvlIf function doesnt return a value, then warnings are
suppressed by this directive while compiling.
4 #pragma warnparIf function doesnt use passed function parameter , then
warnings are suppressed
5 #pragma warnrch If a non reachable code is written inside a program, suchwarnings are suppressed by this directive.
Prev Next
C Dynamic memory allocation
Prev Next
C - Dynamic Memory Allocation:
http://fresh2refresh.com/c/c-type-casting/http://fresh2refresh.com/c/c-command-line-arguments/http://fresh2refresh.com/c/c-command-line-arguments/http://fresh2refresh.com/c/c-variable-length-arguments/http://fresh2refresh.com/c/c-arithmetic-functions/http://fresh2refresh.com/c/c-arithmetic-functions/http://fresh2refresh.com/c/c-arithmetic-functions/http://fresh2refresh.com/c/c-variable-length-arguments/http://fresh2refresh.com/c/c-object-exe-file-creation/http://fresh2refresh.com/c/c-command-line-arguments/http://fresh2refresh.com/c/c-type-casting/ -
7/28/2019 C type cast
14/23
The process of allocating memory during program execution is called dynamic memory allocation.
CDynamic memory allocation functions:
C language offers 4 dynamic memory allocation functions. They are,
1. malloc()2. calloc()3. realloc()4. free()
S.no Function Syntax
1 malloc () malloc (number *sizeof(int));
2 calloc () calloc (number, sizeof(int));
3realloc ()
realloc (pointer_name, number * sizeof(int));
4 free () free (pointer_name);
malloc ():
malloc () function is used to allocate space in memory during the execution of the program. malloc () does not initialize the memory allocated during execution. It carries garbage value. malloc () function returns null pointer if it couldnt able to allocate requested amount of memory.
Example program for malloc() in C:
C
1
2
3
4
5
6
78
9
10
11
12
13
14
15
#include
#include
#include
int main()
{
char *mem_allocation;/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
-
7/28/2019 C type cast
15/23
16
17
18
19
20
21
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}
Output:
Dynamically allocated memory content : fresh2refresh.com
calloc ()
calloc () function is also like malloc () function. But calloc () initializes the allocated memory to zero. But,malloc() doesnt.
Example program for calloc() in C:
C
1
2
3
4
5
6
78
9
10
11
12
13
14
15
16
17
18
19
2021
#include
#include
#include
int main()
{
char *mem_allocation;/* memory is allocated dynamically */
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);}
Output:
Dynamically allocated memory content : fresh2refresh.com
realloc ()
-
7/28/2019 C type cast
16/23
realloc () function modifies the allocated memory size by malloc () and calloc () functions to new size. If enough space doesnt exist in memory of current block to extend, new block is allocated for the full size of
reallocation, then copies the existing data to new block and then frees the old block.
free ():
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns the memoryto the system.
Example program for realloc() and free():
C
1
2
3
4
5
6
7
8
9
10
11
12
1314
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include
#include
#include
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"space is extended upto " \
"100 characters");
}
printf("Resized memory : %s\n", mem_allocation );
free(mem_allocation);
}
Output:
-
7/28/2019 C type cast
17/23
Dynamically allocated memory content : fresh2refresh.com
Resized memory : space is extended upto 100 characters
Do you know difference betweenStatic memory allocation and Dynamic memory
allocation?
S.no Static memory allocationDynamic memory allocation
1
In static memory allocation, memory is
allocated while writing the C program.
Actually, user requested memory will be
allocated at compile time.
In static memory allocation, memory
is allocated while executing the
program. That means at run time.
2Memory size cant be modified while
execution.Example: array
Memory size can be modified while
execution.Example: Linked list
Do you know difference between malloc and calloc?
S.no malloccalloc
1It allocates only single block of requested
memory
It allocates multiple blocks of requested
memory
2
int *ptr;ptr = malloc( 20 * sizeof(int) );For
the above, 20*4 bytes of memory only
allocated in one block.
Total = 80 bytes
int *ptr;Ptr = calloc( 20, 20 * sizeof(int)
);For the above, 20 blocks of memory
will be created and each contains 20*4
bytes of memory.
Total = 1600 bytes
3malloc () doesnt initializes the allocated
memory. It contains garbage values
calloc () initializes the allocated memory
to zero
4
type cast must be done since this function
returns void pointerint *ptr;ptr =
(int*)malloc(sizeof(int)*20 );
Same as malloc () functionint *ptr;ptr =
(int*)calloc( 20, 20 * sizeof(int) );
C int, char validation
Prev Next
The functions used to validate the data type of the given variable are given below with description and
example programs. These are all the inbuilt functions in C language.
S.no Function Description
1 isalpha checks whether character is alphabetic
2 isdigit checks whether character is digit
3 isalnum checks whether character is alphenumeric
http://fresh2refresh.com/c/c-buffer-manipulation-function/http://fresh2refresh.com/c/c-time-related-functions/http://fresh2refresh.com/c/c-time-related-functions/http://fresh2refresh.com/c/c-time-related-functions/http://fresh2refresh.com/c/c-buffer-manipulation-function/http://fresh2refresh.com/c/c-object-exe-file-creation/ -
7/28/2019 C type cast
18/23
4 isspace checks whether character is space
5 islower checks whether character is lower case
6 isupper checks whether character is upper case
7 isxdigit checks whether character is hexadecimal
8 tolowerchecks whether character is alphabetic and
converts to lower case
9 toupperchecks whether character is alphabetic and
converts to upper case
Example program for isalpha():
This function checks whether character is alphabetic
C
1
2
3
4
5
6
7
89
10
11
12
13
#include
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);if ( isalpha ( ch ) )
printf ( "\nEntered character is alphabetic" ) ;
else
printf ( "\nEntered character is not alphabetic" ) ;
}
Output:
Example
program
for
isdigit():
This function checks whether character is digit
C
Enter any character
1
Entered character is not alphabetic
-
7/28/2019 C type cast
19/23
1
2
3
4
5
6
7
8
9
10
11
12
13
#include
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isdigit ( ch ) )
printf ( "\nEntered character is digit" ) ;
else
printf ( "\nEntered character is not digit" ) ;
}
Output:
Enter any character
200
Entered character is digit
Example program for isalnum():
This function checks whether character is alphenumeric
C
1
2
3
4
5
6
7
8
9
10
11
12
13
#include
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isalnum ( ch ) )
printf ( "\nEntered character is alphanumeric" ) ;
else
printf ( "\nEntered character is not alphanumeric" ) ;
}
Output:
-
7/28/2019 C type cast
20/23
Enter any character
@
Entered character is not alphanumeric
Example program for isspace():
This function checks whether character is space
C
1
2
3
4
5
6
7
8
9
10
11
12
13
#include
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isspace ( ch ) )
printf ( "\nEntered character is space" ) ;
else
printf ( "\nEntered character is not space" ) ;
}
Output:
Enter any character
a
Entered character is not space
Example program for islower():
This function checks whether character is lower case
C
1
2
3
4
5
#include
int main()
{
char ch;
-
7/28/2019 C type cast
21/23
6
7
8
9
10
11
1213
printf("Enter any character\n");
scanf("%c", &ch);
if ( islower ( ch ) )
printf ( "\nEntered character is lower case character") ;
else
printf("\nEntered character is not lower case character");}
Output:
Enter any character
a
Entered character is lower case character
Example program for isupper():
This function checks whether character is upper case
C
1
2
3
4
5
67
8
9
10
11
12
13
#include
int main()
{
char ch;
printf("Enter any character\n");scanf("%c", &ch);
if ( isupper ( ch ) )
printf ( "\nEntered character is upper case character") ;
else
printf("\nEntered character is not upper case character");
}
Output:
Enter any character
A
Entered character is upper case character
Example program for isxdigit():
This function checks whether character is hexadecimal
C
-
7/28/2019 C type cast
22/23
1
2
3
4
5
6
7
8
9
10
11
12
13
#include
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isxdigit ( ch ) )
printf ( "\nEntered character is hexadecimal" ) ;
else
printf ( "\nEntered character is not hexadecimal" ) ;
}
Output:
Enter any character
#
Entered character is not hexadecimal
Example program for tolower():
This function checks whether character is alphabetic and converts to lower case
C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if(isalpha(ch))
printf ( "\nEntered character is converted into " \
"lower character : %c\n",tolower ( ch ) ) ;
else
printf("Entered character is not an alphabetic");
}
Output:
-
7/28/2019 C type cast
23/23
Enter any character
A
Entered character is converted into lower character : a
Example program for toupper():
This function checks whether character is alphabetic and converts to upper case
C
1
2
34
5
6
7
8
9
10
11
12
13
14
#include
int main(){
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if(isalpha(ch))
printf ( "\nEntered character is converted into " \
"upper character : %c\n",toupper ( ch ) ) ;"
else
printf("Entered character is not an alphabetic");
}
Output:
Enter any character
a
Entered character is converted into upper character : A