Showing posts with label C Qualifiers - Constant and Volatile type Qualifier. Show all posts
Showing posts with label C Qualifiers - Constant and Volatile type Qualifier. Show all posts

Thursday, January 14, 2016

Implicit and Explicit Type Casting

Type casting can either be performed by the compiler automatically or user can specify them using the syntax described above. Former type is called implicit type casting and the latter is called explicit type casting.
What is implicit type casting/ implicit type conversion?
We've explained the explicit type conversion in the above paragraphs. Now lets's take a look at how implicit type conversion works. In implicit type conversion compiler takes care of the casting without requiring the programmer to specify them explicitly. For example in the program given below, compiler converts the sum of two float numbers to an int.
  1. ##include <stdio.h>
  2.  
  3. int main()
  4. {
  5. float value1 = 2.2;
  6. float value2 = 3.3;
  7. int result;
  8.  
  9. result = value1 + value2;
  10. printf("Result : %d", result);
  11. return 0;
  12. }
  13.  
  14. Output:
  15. Result : 5
Note: Though compiler performs implicit type casting, it's always recommended to specify the conversion explicitly because this improves the code readability and makes it easier to port to other platform.

Tuesday, January 12, 2016

C Qualifiers - Constant and Volatile type Qualifier

C has some basic data types like 'int', 'float', 'char' etc. Each of which can hold a data of a specific type and has a set of specific properties defined for them. But what if you need to modify the properties of them? For example, if you want to make an 'int' variable constant, that means it's value shouldn't be changed from any where else in the program except the variable definition part. C type qualifiers can be used for such purposes.

'Const' Qualifier in C

Two type qualifiers available in C are 'const' and 'volatile'.
'Const' qualifier will impose a restriction on the variable, such a way that its value can't be changed or modified. The main use of 'const' is to define constants in your program; so that it's values can't be changed. Please take a look at the example given below to understand the use case of 'const' qualifier
  1. #include <stdio.h>
  2. // PI is defined as 'const' so that you may not change it's value accidentally.
  3. const float PI = 3.14;
  4.  
  5. double find_area(float radius) {
  6. return PI * radius * radius;
  7. }
  8.  
  9. int main() {
  10. printf("Area: %f", find_area(5.5));
  11. return 0;
  12. }
  13.  
  14. Output:
  15. Area: 94.985001

'Volatile' Type Qualifier in C

If a variable is declared as 'volatile', its value can be changed from outside the program. Declaring a variable with 'volatile' is actually a hint to the compiler to not perform any optimizations on the access restrictions of the variable. Let's take a look at it with the help of an example using 'volatile' keyword.