Type Casting, Command Line Arguments and Defining Constants
Type Casting
• Type cast is an instruction to the compiler to convert one type into another.
• For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'.
• You can convert the values from one type to another explicitly using the cast operator as follows: (type_name) expression
• When a cast involves a narrowing conversion, information might be lost.
• For example, when casting a long into a short, information will be lost if the long’s value is greater than the range of a short because its high-order bits are removed.
EX:-
#include
int main()
{
int sum = 17, count = 5;
double mean;
mean = sum / count;
printf("Value of mean : %f\n", mean );
return 0;
}
#include
int main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean ); return 0;
}
Command Line Arguments
• It is possible to pass some values from the command line to your C programs when they are executed.
• These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.
• The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program.
• It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument.
• If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2.
Ex:-
#include
printf("The first argument supplied is %s\n", argv[0]);
printf("The second argument supplied is %s\n", argv[1]);
printf("The third argument supplied is %s\n", argv[2]);
return 0;
Ex:
#include
Defining Constants
- There are two ways to define constant in C programming:
- Using the const key word.
const data_type constant_name = constant_value; const float PI = 3.1412;
- Using the #define directive.
- #define come before the program main block.
#define constant_name constant_value
#define PI 3.1412
Ex:-
#include
const float PI = 3.1412;
float radius;
printf ("Enter the radius in mm : \n");
scanf ("%f",&radius);
printf("The perimeter is : %.2f", 2*PI*radius);
return 0;
Comments
Post a Comment