Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Rückgabeanweisung in Funktionen | Einführung in Funktionen
C++ Einführung
course content

Kursinhalt

C++ Einführung

C++ Einführung

1. Erste Schritte
2. Einführung in Operatoren
3. Variablen und Datentypen
4. Einführung in den Programmfluss
5. Einführung in Funktionen

book
Rückgabeanweisung in Funktionen

Die return-Anweisung beendet die Ausführung einer Funktion und gibt einen Wert eines vordefinierten Typs zurück.

h

function

copy
12345
int func() // int - predefined { int variable = 10; return variable; // variable = 10 }

Wenn der Typ falsch angegeben wird, verhält sich die Funktion unvorhersehbar.

cpp

main

copy
12345678910111213
#include <iostream> unsigned short func() { return -10; } //The unsigned short data type has no negative values. int main() { std::cout << func() << std::endl; }

Das heißt, bevor Sie eine Funktion erstellen, muss der Datentyp, den sie zurückgibt, festgelegt werden. Außerdem gibt es in C++ spezielle void-Funktionen. Funktionen dieses Datentyps dürfen nichts zurückgeben:

cpp

first_example

cpp

second_example

copy
12345678910111213
#include <iostream> void voidFunction() { std::cout << "It's void function!" << std::endl; //function without return } int main() { voidFunction(); }

Es kann mehrere return-Anweisungen in Funktionen geben, und jede wird nur unter bestimmten Bedingungen ausgeführt.

cpp

main

copy
123456789101112131415161718192021
#include <iostream> int func() { int a = 50; int b = 6; if (a > b) //if a > b, func will return a { return a; } else //otherwise func will return b { return b; } } int main() { std::cout << func() << std::endl; //func calling }

Wenn es zwei return-Anweisungen gibt, wird die zweite return-Funktion ignoriert:

cpp

main

copy
12345678910111213141516
#include <iostream> int func() { int a = 50; int b = 6; return a; return b; } int main() { std::cout << func() << std::endl; //func calling }

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 5. Kapitel 3
We're sorry to hear that something went wrong. What happened?
some-alt