DEV Community

Cover image for Functions in C++
Saloni Goyal
Saloni Goyal

Posted on • Updated on

Functions in C++

In C++, you can write functions that make things happen.

  • To use a function, you call it.
  • Before you can call a function, the compiler must know what it is--declare it.
  • Somewhere in your program you must implement it--define it.
  • This can be anywhere, the linker will link the function to the code that calls it.

Alt Text

  • defining a function also declares it
  • functions have a return type
  • here, add has a return type int.
  • just as with declaring variables the type comes before the variable name, while defining a function we put the return type before the function name.

Parameters

  • The values in the round braces or parenthesis are called parameters.
  • Some functions don't take any parameters ().
  • Parameters are separated by commas, where each of them looks like a variable declaration.

int x

  • Functions take parameters which have a name and a type.

Alt Text

  • When you call the add function, you don't have to pass it variables that are called x and y in the calling scope but that is what they will end up being called inside the function.

int a = add(3,4); // called add at 3,4

makes a call to the add function with x = 3, y = 4 and then add returns 3 + 4 = 7, which is then put into a.

main is also a function we have been writing so far.

A function to add two integers

Alt Text

The compiler enforces type rules when you call a function.

Most of the time, you don't write a function if you are only going to call it once and especially not if it is one line long.

Functions really come into their own when they let you achieve some kind of abstraction. Something complicated like calculating sales tax that can be put into a function and used without knowing the underline working of calculating sales tax.

Clean Code Tip: Function should be readable in one go, not having to read up and down.

Don't Repeat Yourself (DRY): With functions, you save on writing the same piece of code again and again.

TODO: Write a function that allows to add two doubles.

Code for reference.

Please leave out comments with anything you don't understand or would like for me to improve upon.

Thanks for reading!

Top comments (0)