C++ return Keyword

πŸ”™ C++ return Keyword

The return keyword in C++ is used to send a value back from a function and terminate the function execution.


πŸ”Ή 1. Basic Syntax

return value;

or (for void functions):

return;

πŸ”Ή 2. Simple Return Example

int add(int a, int b) {
return a + b;
}

int result = add(10, 20);
cout << result; // 30


πŸ”Ή 3. Return Multiple Times (Conditional Return)

int check(int x) {
if (x > 0)
return 1;
else
return -1;
}

➑ Function exits as soon as return is executed.


πŸ”Ή 4. Return in void Function

void print(int x) {
if (x < 0)
return; // exits function
cout << x;
}

πŸ”Ή 5. Returning Expressions

int square(int x) {
return x * x;
}

πŸ”Ή 6. Returning a Reference

int& getMax(int &a, int &b) {
return (a > b) ? a : b;
}

⚠️ Must return a reference to an existing variable (not local).


πŸ”Ή 7. Returning a Pointer

int* getAddress(int &x) {
return &x;
}

πŸ”Ή 8. Return an Array (Using Pointer)

int* createArray() {
int *arr = new int[3];
return arr;
}

⚠️ Caller must delete the memory.


πŸ”Ή 9. Return Struct or Class Object

struct Point {
int x, y;
};

Point getPoint() {
return {10, 20};
}


πŸ”Ή 10. Return vs cout

int sum(int a, int b) {
return a + b;
}

βœ” return sends data back
❌ cout only prints


❌ Common Mistakes

void func() {
return 10; // ❌ invalid
}
int func() {
// missing return ❌
}

πŸ” return and main()

int main() {
return 0;
}
  • 0 β†’ successful execution

  • Non-zero β†’ error code


πŸ“Œ Summary

  • return sends a value back to the caller

  • Immediately ends function execution

  • Required for non-void functions

  • Can return values, references, pointers, objects

  • return; can be used in void functions

You may also like...