# Extract function

> **TL;DR**
> `Refactor | Extract/Introduce | Method`
>
>
>
> `Ctrl+Alt+M` (Windows), `⌘ ⌥ M` (macOS), `⌘ ⌥ M` (IntelliJ IDEA Classic (macOS)), `⌘ ⌥ M` (macOS System Shortcuts), `Ctrl+Alt+M` (XWin), `Ctrl+Alt+M` (GNOME), `Ctrl+Alt+M` (KDE), `Ctrl+Alt+M` (Emacs), `Ctrl+Alt+M` (Sublime Text), `⌘ ⌥ M` (Sublime Text (macOS)), `⌘ ⌃ ⌥ M` (Xcode), `Ctrl+R, M` (Visual Studio), `⌘ R, M` (Visual Studio (macOS)), `Ctrl+Alt+M` (ReSharper), `⌘ ⌥ M` (ReSharper (macOS)), `Ctrl+Alt+M` (QtCreator), `⌘ ⌥ M` (QtCreator (macOS)), `Alt+Shift+M` (NetBeans), `Alt+Shift+M` (Eclipse), `⌘ ⌥ M` (Eclipse (macOS))

When the Extract Function refactoring is invoked, CLion analyzes the selected block of code and detects variables that are the input for the selected code fragment and the variables that are output for it.

The detected output variable is used as a return value for the extracted function.

Procedure: Extract a function

1. In the editor, select a block of code to be transformed into a function.

> **Tip:**
> The code fragment to form the method does not necessarily have to be a set of statements. It may also be an expression used somewhere in the code.

2. From the main menu or from the context menu of the selection, select `Refactor | Extract/Introduce | Method` or press `Ctrl+Alt+M` (Windows), `⌘ ⌥ M` (macOS), `⌘ ⌥ M` (IntelliJ IDEA Classic (macOS)), `⌘ ⌥ M` (macOS System Shortcuts), `Ctrl+Alt+M` (XWin), `Ctrl+Alt+M` (GNOME), `Ctrl+Alt+M` (KDE), `Ctrl+Alt+M` (Emacs), `Ctrl+Alt+M` (Sublime Text), `⌘ ⌥ M` (Sublime Text (macOS)), `⌘ ⌃ ⌥ M` (Xcode), `Ctrl+R, M` (Visual Studio), `⌘ R, M` (Visual Studio (macOS)), `Ctrl+Alt+M` (ReSharper), `⌘ ⌥ M` (ReSharper (macOS)), `Ctrl+Alt+M` (QtCreator), `⌘ ⌥ M` (QtCreator (macOS)), `Alt+Shift+M` (NetBeans), `Alt+Shift+M` (Eclipse), `⌘ ⌥ M` (Eclipse (macOS)).

3. In the Extract Function dialog that opens, specify the name of the new function, the return type, and other settings.

![Extract method dialog](https://resources.jetbrains.com/help/img/idea/2026.2/cl_extractMethodDialog.png)

If the function has not been yet declared, select the declaration place: above or below current place.

In the parameters pane:

* Add the new parameters or delete the unnecessary ones

* Rename parameters or/and change their types by clicking the corresponding parameter lines and entering the new names and types

* Reorder parameters in the list

* Change the return type of the function

You can make a function `constexpr` or `noexcept` using the corresponding checkboxes.

4. Check the result in the Signature Preview pane and click Extract to create the function.

The selected code fragment will be replaced with a function call.

| Before | After |
| --- | --- |
|     ```CPLUSPLUS int main() {     int x = 15;     int y = 10;      int z = x - y;      return 0; } ```    |     ```CPLUSPLUS int main() {     int x = 10;     int y = 15;      int z = XSubY(x,y);      return 0; }  void XSubY(int x, int y) { return x - y; } ```    |

