Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Saturday, 21 March 2015

Volatile Keyword


In this post I am going to describe why we use volatile keyword.

I am assuming you have a basic knowledge of compiler. Whenever we write a code and compile it. Compiler optimizes our code according to some basic fundamentals.

Like for eg. If in our code we have a constant variable whose value cannot be modified and we have a loop checking this constant variable with another constant. Means if compiler thinks that none part of our code is changing the value of the variable than it can optimize the comparisons.

Ex:
I am not writing the complete code. I am writing only the part which considers the above fact.

const int a=10;

while(a<20){    /// focus on this line
      some task;
}
Now At compile time compiler will check that variable a is constant and its value cannot be changed. And in the while loop it determines that 20 is also constant so it is also not changed. So it evalutes the result of a<20 and put it in the while condition.

Then compiler will put either true or false there to optimize. So that at each time it iterate through the loop it does not have to compare the variable.

For ex: After optimization code looks like this.

const int a=10;

while(true){   /// focus on this line
      some task;
}

But sometime this optimization affect the code in the wrong way.
Like : If we have a share variable between two files or two program then we don't want compiler to do any optimization with those variables. 

In this case we can define those variables to volatile. So compiler will not apply any kind of optimization on these variables.

Scenario 1: Variable with Volatile Keyword :

Ex:  we have a variable called a which is shared in two threads thread1 and thread2.

Volatile Keyword


Explanation: We have a volatile variable a=1 in thread 1 and it is shared. When thread 1 runs it goes in to while loop and check for a and goes in to the loop and do the task and switch to thread 2. Now thread 2 also checks a=1 goes in to loop and make a=0 and then again switch to thread 1 at line 8.

Now it checks the value of a which is equal to 0 and come out of the loop.


Scenario 2: Variable without Volatile Keyword.

Now consider the scenario where value of a is optimized. Means without volatile.

In thread 1;
int a=1;

some task;
while(a){  /// this is replaced by while(1)   /// optimized by compiler    ///// line 1
    do some task;  
   switch to thread2;
   //// line8
}


In thread 2:

while(a){
   do some task;
    a=0;
   switch to thread 1;
}


Explanation: We have a variable a=1 in thread 1 and it is shared. When thread 1 runs it check for a and goes in to the loop and do the task and switch to thread 2. Now thread 2 also checks if a!=0 and goes in to loop and make a=0 and then again switch to thread 1 at line 5.

Due to while(1).
Now because of optimization thread 1 now do not check the value of a at line 1.

And goes into infinite loop. A serious problem caused due to optimization. 

So for avoiding this problem use volatile keyword to the variables which we do not want compiler to optimize in any case.



I hope it helps. If you find this useful share it. If you have any problem feel free to comment. How do you rate this post either interesting or cool or funny. See below. Thanks for visiting.


Thursday, 18 December 2014

Type Conversion/ Type Casting

Q. What is Type Conversion, how and when it happens?
Ans. When we write an expression in any language it would have some operators and operands. When there are two different types of operands (like: int and float) along with an operator(like: + or * etc.) then the operands are converted to a common type according to some rules( specifically in C ).

Example:
long int j=100000000000;
int i=10;
long int k=i+j;

then the value of i is automatically converted in to long for evaluating the expression and result will be long int. 
Note: the value of i is still 10 and type of i is still int. It just change the value of i to the long int temporarily for the expression evaluation.

      This conversion is called type conversion. It is happening by default automatically so it is called automatic type conversion. Which converts the "narrower range(like int)" operand to a "wider range (like long int)" operator. In this type of conversion no information is lost.

     We can forcefully convert any "wider range operand" to a "narrower range operand". The compiler will not give an error. But there is always a drawback of losing information in this type of conversion.
Ex: 
long int j=100000000000;
int i=(int) j;  /// type casting , converting value of j in to range of integer.

in this type of code compiler may not give an error but the value of i will not be equal to the value of j because j is containing value which is beyond the range of the integer variable. It is called type casting.

General Rules for automatic conversion( in C):
1. If one of the operand is long double, other will be converted to the long double.
2. Else if one of the operand is double, other will be converted to the double.
3. Else if one of the operand is float, other will be converted to the float.
4 .Else char and short int is converted in to int.

5. Then, if either operand is long, other will be converted in to long.

Note: So while doing type casting on your own always take care of not converting a wider range operand to a narrower range operand. Otherwise some information may be lost.
 Type conversion can be done while calling a function also.
Ex:
int m=10;
sqrt((double)m);

The in build function sqrt of the math.h library expect a double argument to it. If we want to find sqrt of an int then we can convert it to double while calling function. The value is converted to double and then send to the function.

Note: Again the value and the type of the m is still not changed.

 Stay tuned for the new posts and leave comment or ask questions if u have any :)


Monday, 10 November 2014

Multifile programming

Q. What is multifile programming and why we use multifile programming concept?
Ans. First of all what is multifile programming.

You might have heard of your teacher saying "use multifile programming to do this assignment".

So multifile programming is to do the programming in a manner that its all functions become reusable by just including a file in the other programme. Easier to understand and modify.

Actually in multifile programming we write the functions declarations and definitions in two different files. Function declaration in .h file or any other extension except the reserved extension like .c /.cpp etc. And then we write the functions definition in the other file but different extension .c/.cpp. Then we make the object file of that c/cpp file using command gcc -c filename.c .

Do not forget to include .h file in you .c/.cpp file. Then we write the main file . In which we use the functions which we have declared in .h and defined in .c/.cpp file.

Here it goes the complete process
1. Make a header file including all functions declaration and you can declare the global variable also here but not the static variable, I will define the reason for this in future posts.
fun.h -> contains all the function declaration and may be global variable declarations

2. Make a .c/.cpp file fun.c which implements those functions written in fun.h. Remember to add the .h file in .c/.cpp file . Do not define main function in this fun.c file . Define only the functions which we have declared in fun.h. Then do no compile it as usual ways . 
                      Compile it like gcc -c fun.c.
Because it creates a object file not and executable file. Because it do no contain main function you can not compile it usual ways. Other wise it will give error main function is missing.

3. Make a main file mainfile.c/.cpp . Which does the task what we want to do using those functions.
Now while compiling this file do not remember to add the object file we made in the second step.
Ex.   gcc -o executable mainfile.c fun.o

-o rename the executable file as executable and we add the fun.o file to the mainfile so it does not miss any function definitions. 
Then run file as ./executable.

The reason why we are doing this because.
Suppose we want to give some developer information that they can use our functions but they can not see implementation. Then we can give him/her our header files containing function declaration and the object file. No need to give fun.c to anyone. No one will knows our implementation.

Another scenario is when we want to use those function in some other file include that header file and add that object file while compiling. 
I am sorry , I explained it only as linux user.

Sunday, 9 November 2014

Recursion

Q. What is recursion and why we use it?

Ans. As the name suggest recursion is to call something or do something again and again.

In programming language if a function invokes itself or in lay man language a function call itself. Then this programming paradigm is called recursion.

Recursion is very useful in some situations.  Like: finding the factorial.
But every coin has two faces. So Recursion also has some cons.

Ex:

int find_fact(int k){

       if(k==0 || k==1)
             return 1;

       else 
             return  k* finf_fact(k-1);
}

In this function we call find_fact again till we reach the termination condition which is k==1.

Before writing any recursive function we should think of what will be its terminating condition. Our calls to the same function should converge to termination point . It should not deviate away from the termination point otherwise it may go in to infinite loop.

Ex. 
if in above example I write k+1 instead of k-1 and if user send 2 as input to function then this will never going to be terminated. Because it is going away from the termination point. Recursive call should be converging to the termination point.

Any recursive function or program can be written without recursion but not other way around.

In recursive function in built stack of computer is used. It keeps all the information of the call at which line function is invoked. It puts that function frame to the top of the stack and then function returns it reach to the last address where it left the function and start evaluating again.

But as the number of calls increases the stack size increases. So for large number of inputs there might be segmentation fault due to stack overflow. So avoid the writing functions using recursion . Try to write it without recursion and use your stack so you know what is the size of the stack. Whether it is overflowing or not.

To find the complexity of the recursive function we write the recursive equation and try to solve it using Master's theorem or tree method or induction any of these or any other method.

Ex. the recursive equation of the above function is
               
T(n) = T(n-1) + C;                       

C is here some constant it may be zero or anything. It depends on the function. Here No loops in the function only just a condition and a multiplication expression so C's value here is turn to be 1.

By solving this you can get the complexity. I am leaving this is an easy exercise to do on your own.

Saturday, 8 November 2014

Structure vs Class

Q. Why we use Structure or Class and when to use them ?

Ans. In the past when there was no concept of OOPS programming there was no class concept. 

Then how could we implement a real time entity (in C) and then later convert to object (in OOPS).
At that time structure was very useful to implement a real world entity in the programming. Like for example we have to make car's object or entity. Then we can use Structure name as car which can have the car's attribute. But at that time structure could not contain functions associated with the entity.

Ex.  structure definition

      Struct car {
               bool petrol;           /// It is running from petrol or diesel
               int engine_type;
               long int price;
               int capacity_seat;
               ..............etc....

};

In the above structure we map the real world car to that structure with the similar attributes what a real world car would have. But we can not define the function of the car in that structure and that is the main difference between the C structure and C++ class concept.

There is no concept of access specifier in C structure but in C++ concept of access specifier is there. A member or a member function of a class can either be public, private or protected depending upon the needs.

Ex.
            Class car{
             
             private:
               bool petrol;           /// It is running from petrol or diesel
               int engine_type;
               long int price;
               int capacity_seat;
               /////..............etc....
             public:
               // constructor which makes an object of the car
               car(int a, bool b, ////etc.....){

               }

             // destructor which destruct the object
            
             ~ car(){
                // some implementation
                  }

           } ;

In class we can define the function also. There is a concept of the constructor and destructor in oops.

Mainly differences are

                         Structure  in C                                                       Class in OOPS (C++)

1.       Do not contain function of the entity.             May contain functions of Object.

2.       No concept of access modifier.                       Member can be public , private or protected

3.       No constructor or destructor.                           Every class contains a constructor and 
                                                                                   destructor either  in 
                                                                                   built or user defined .

Thursday, 6 November 2014

Write a function

Q. How to write a function and why we need them?
Ans. First of all why we need function.

Suppose we have to write a programme for L.C.M. (least common multiple) for two integers . We wrote the programme without using function and someone now ask to write the same programme for more than two integers. But now we cannot use the same programme for it. But If we would have written that programme in a function then we could have used that function for extension.

If we have to find the l.c.m. twice in the same programme then we have to write the code twice if we are not making a function of the l.c.m.


There are more advantages.
1. We don't have to rewrite the code again and again. (Code length is reduced)
2. We can use those function in other programmes but if do not write in functions we can not re use them. (Extendability)
3. Easy to read and understand. (User and programmer friendly)


How to write functions?

Functions always have their prototype. Means what is the function's name and what function take as argument and what does function return etc.. I will explain it in the next part.

Prototype:(function declaration)
Return_type function_name ( function's arguments);

Ex.  int add(int val1, int val2);

In this prototype function's return type is int means function will return a integer. Function name is add and it takes two argument val1 and val2. It is just a prototype. Function will also have a body. In which we define what function really does?

(function definition)
Ex.
 int add(int val1, int val2){             //function body starts
      int result= val1+val2;
      return result;

}

Function's body is written between the paranthesis. Here we define a temporarily variable which is not necessary. We add the two values and return the result through return keyword.

We could have written it this way also.

int add(int val1,int val2){
       return val1+val2;
}

This is also correct. It automatically allocate a temporarily variable and calculate the result and then return the result.

Prototype is not necessary if you define function before it is used. But now in new gcc compiler (2014) there is no need to write prototype or declaration . You can directly define function anywhere in the programme. Remember it is true only for the latest gnu gcc compiler.


Wednesday, 8 October 2014

Macros

Q. Why we use macros?
Ans. First of all What is macros?

Macros are used to define something before the execution starts and its values are never changed during the execution.

Ex:  in c/c++

#define max_size 100
#ifndef
#include<something.h>
#end if

Imagine the scenario you write a program where you assume the size of the input to 1000 at max and u use every where 1000 . Then some one asked you to modify that program for 10000 elements then you have to go to all places where you write that 1000 and replaced it by 10000 instead of that we can use macros we define variable in starting outside the main function and use that variable in our function if some one asked to change the size we change only that variable and the changes at all the places are taken care of automatically.

Macros are predefine variables or function. Compiler replaces all the macros in its pre processing with its corresponding values in the entire program.



Argument to main function in C/C++

Q. What is the use of passing argument to main function?
Ans.
      First of all we can define main function in three different format in c/c++.
      int main(int argc,char * argv[]);
      int main(void);
      int main();

Instead of int return type we can have any other pre defined data type as return type of main function.

We start with the first prototype, here main function excepts two arguments one is of type int and other is of type array of pointers. First of all these arguments are used for passing the input together when we start executing the program. We don't have to pass the first argument it automatically counts how many argument we have passed while executing the program and that will be stored in argc.

Second argument argv[] is array of character pointers which stores the inputs which we have sent with execution. for ex. argv[0] will have first argument and argv[1] will have second argument .


In the second prototype it does not except any argument if we passes a argument the compiler will give an error.

Third one is similar to the second one but the difference is that in third one we can pass as many argument we want it will not give an error but in the second one it will give an error while we pass an argument to main function using terminal (linux users).

Header files

The question always comes to our mind is why we include header files?

Ans:  The answer is simple The function which we use can be define separately in .h files. .h is the extension of header files which contains the prototype of the function and also may contain the definition but for reason of abstraction we prefer to write prototype and definition in different file prototype in .h but not necessary can be written with some other extension also.

Then we write the definition to .c file compile those files make their object files and include header file to our main file and put both .h and .c file to the same folder then use the functions written in that header file. Some header files are already in-built which we can directly use like #include<stdio.h> it is a standard input output file which we can use for printf and scanf functions etc.

The advantage is our source code file's size is less. And if we want to give someone which functions are available we can give the header .h file only. No need to give .c file we can give object file so he/she will not need to understand how the implementation is happening.

Tuesday, 7 October 2014

Increment operator in c

Are you ready for some serious brain storming?
Here it goes my first post.

1. What would be the output of this program while running with the gnu gcc compiler?


#include<stdio.h>

int main(int argc, char * argv[]){

      int z=2;
      int y=2;
   
      z=z++;
      y=++y;
      printf("%d  %d",z,y);
 return 0;
}

Please Before proceed to answer just think for a minute.
Think ::::


This Space is left intentionally.









Although this is undefined behavior due to absence of sequence point. I will define sequence point in my future posts. But here I am presenting one of the reasons of getting this output.




Answer is  : 2 3

Reason is : For understanding the reason behind this we have to understand the execution sequence of instruction z=z++;

For evaluation of a expression compiler generates a temporary variable and evalute the expression and store the value in the temporary variable which in the given expression is 2 because postfix operator executes after the expression is evaluated. So till now the temporay variable has value 2 
and now z becomes three due to posfix operator. And then the temporary variables value is assigned to the variable which is on the left side of the = operator which here is z itself so value 2 is assigned to z again.
Finally the value of z becomes 2.

Similarly for the value of y first expression is evaluated and in this pre increment is also evaluated so value of y becomes 3 and the value of temporary variable is also becomes 3 and now this temporary variable's value is assigned to y.
Finally the value of y becomes 3.

Related Posts

Related Posts Plugin for WordPress, Blogger...