Function - C P P

Theory


  • Function Call Stack => LIFO
  • Scope => Variable can only be accessed inside that Block
  • Types
    • Inline Function
      • Used to reduce the function calls overhead
            inline returnType functionName(dataType& var1) {
                return var2;
            }
        
      • Should be 1 line, Compiler decides if 2 or 3 lines, Not for more than 3 lines
      • Replaces code just like Macro
    • Const function
      • For const return type
            const returnType functionName(dataType var1) {
                return var2;
            }
        
      • For const return type and const parameter
            const returnType functionName(const dataType var1) {
                return var2;
            }
            // Const value needs to be passed
            const dataType variable = value;
            functionName(variable)
        
  • Return by Reference, Bad Practice, Local variable is being sent
        int& functionName(int var) {
            int num = a;
            int& ans = num;
            return ans;
        }
    

Syntax


  • Function
      returnType functionName(argument var1) {
        // Statement
        return var2;
      }
    
  • Function with default parameter, Default should always be the right-most argument
      returnType functionName(dataType=value) {
        // statement
      }
    
  • Calling a Function
    • Pass by Value, Copy is created
          returnType functionName(int var) {
              // statement
          }
          functionName(var);
      
    • Pass by Reference, Using reference variable, No new memory is created
          returnType functionName(int& var) {
              // statement
          }
          functionName(var);
      
Share: