Trailing Return Types

Trailing Return Types and auto

How do trailing return types relate to the auto keyword in C++?

Abstract art representing computer programming

Trailing return types and auto are closely related when defining functions. When you use a trailing return type, you must use auto in place of the actual return type before the function name. For example:

auto Add(int x, int y) -> int {
  return x + y;
}

Here, auto essentially acts as a placeholder, indicating that the actual return type will be specified after the parameter list using the -> syntax.

This is different from using auto without a trailing return type:

auto Subtract(int x, int y) {
  return x - y;
}

In this case, auto tells the compiler to deduce the return type from the return statement. The function will return an int, but that type isn't explicitly specified in the function signature.

So in summary:

  • auto with a trailing return type: the auto is a placeholder and the actual type is specified after the ->
  • auto without a trailing return type: auto tells the compiler to deduce the return type
This Question is from the Lesson:

Trailing Return Types

An alternative syntax for defining function templates, which allows the return type to be based on their parameter types

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Trailing Return Types

An alternative syntax for defining function templates, which allows the return type to be based on their parameter types

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved