Things to note about Functions in C plus plus (C++)

Spread the love
  • While passing arguments, the function creates copies of the arguments passed to it. This type of passing arguments is called passing by value.
  • We can pass structure as arguments.
  • We can also return a structure. Useful while returning multiple values.
  • Passing by reference :
    • e.g. void intfunc(float& a, int& b);
  • We can also pass structures by reference.
  • References don’t exist in c.
  • Types of Recursion :
    • Linear Recursion
    • Binary Recursion
    • Tail Recursion
    • Read More : Go Here
    • Back up of above article : P1 P2 P3
  • Inline functions : Use ‘inline’ keyword in function declaration or declarator.
    • inline keyword is actually a request to compiler. Sometimes compiler will ignore the request and compile the function as a normal function.
    • inline functions are similar to #define in C. But inline functions provide better type checking and do not need special care with parenthesis.
  • Scope and Storage class : The scope of variable determines which parts of program can access it and it storage class determines how long it stays in existence.
  • Types of scope : Local (in current block) and file scope (through out a file).
  • Storage classes : Automatic (lifetime of function in which defined) and static (lifetime of program).
  • Variables inside a function called local variables or automatic variables.
    • Automatic name is used because variables are created automatically when function is called and destroyed when function returns.
  • Non initialized local variables will have garbage value.
  • Non initialized global variables will have 0 value.
  • Static variable :
    • Scope of local variable
    • Lifetime of global variable.
  • Local variable and function arguments are stored in stack and global and static variables are stored on heap.
  • Return by reference :
    • int& func();
    • Can call it :   func() = 15;  —  It gives value of 15 to variable returned by function func.
    • We can’t do two things :
      • Can’t return constant.
      • Cannot return local variable reference.
  • ‘const’ function argument : To protect the modification of variable passed by reference.
    • e.g.  void func(const int& a);