HelpWhen to use return function

Posts 1–4 of 4 · Page 1 of 1
When to use return function
Hey, im new to c++ when do I use the return 0; alot of people have told me after I am finished writing the program. Others have told me it is only under certain circumstances. What would these circumstances be?
Quote Originally Posted by Hunter's Panda View Post
Hey, im new to c++ when do I use the return 0; alot of people have told me after I am finished writing the program. Others have told me it is only under certain circumstances. What would these circumstances be?
Calling a function is like breathing, you just do it lol.

As for the return it's what you're wanting to get from the function.

Code:
int add(int i, int p)
{
        return i + p;
}
Return 0 specifically if you want to end a function prematurely because of some errors

Say you're do some file manipulation, reading some text files, doing a query searching for a specific value and the text file doesn't open. This is like the motherload of text files, 97KB big, thousands of lines, it has ALL your data, and the file doesn't open

Code:
#include <fstream>
#include <string>
#include <iostream>

int main()
{
	std::ofstream fileRead;
	std::string line;

	fileRead.open("c:\\My Awesome Text File.txt");

	if (!fileRead) {
		std::cout << "Failed to open \"My Awesome Text File.txt\"\nClosing" << std::endl;
		return 0;
	}

	/* process file like normal */

	return 0;
}
Quote Originally Posted by InunoTaishou View Post
Calling a function is like breathing, you just do it lol.

As for the return it's what you're wanting to get from the function.

Code:
int add(int i, int p)
{
        return i + p;
}
Return 0 specifically if you want to end a function prematurely because of some errors

Say you're do some file manipulation, reading some text files, doing a query searching for a specific value and the text file doesn't open. This is like the motherload of text files, 97KB big, thousands of lines, it has ALL your data, and the file doesn't open

Code:
#include <fstream>
#include <string>
#include <iostream>

int main()
{
	std::ofstream fileRead;
	std::string line;

	fileRead.open("c:\\My Awesome Text File.txt");

	if (!fileRead) {
		std::cout << "Failed to open \"My Awesome Text File.txt\"\nClosing" << std::endl;
		return 0;
	}

	/* process file like normal */

	return 0;
}
ah thanks so much I understand
Basically what I've been doing is putting it on different sections of errors to debug my code.
For example, say it [1]opens a text file, [2]reads it and [3]prints it.
Return 0 right at the end to say it finished fine, and return 1/2/3 on each of the sections above to debug and see where my code wasn't working.
Posts 1–4 of 4 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us