Can someone explain why only one of my functions prints to console? - c++

Here is my code in C++:
#include <iostream>
using namespace std;
int tuna = 20; // this is global
//main function
int main()
{
int tuna = 69; // this is local
cout << tuna << endl;
}
//fish function
int fish()
{
cout << tuna << endl; // this should print global?
}
The fish function doesn't print to the console when I run it. I am not sure why and it doesn't make sense to me.

You are not calling fish() so it doesn't seem strange its body is is not executed.
Try with:
int main()
{
fish();
return 0;
}
because main() is the only possible entry point for your program and the only way to call other, user-defined, functions.

Do you ever call the function (fish) ? Not in your sample.

Because you don't call it at all.

Related

How do I continue to the second main2() from main()? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a problem. Here is the simplified version:
#include <iostream>
using namespace std;
int main() {
cout << "Hello!";
return 0;
}
string name = "My name is ______";
int main2() {
cout << name;
return 0;
}
I have tried to remove the first return 0; in the main(), but it did nothing. I want to somehow start main2() from main(). Is it possible?
I tried running the code(I use repl.it) and it didn't return any error messages. I also tried running it from the Terminal and it just prints Hello!.
Yes. Try something like this:
#include <iostream>
using namespace std;
// Forward declare |main2|.
int main2();
int main() {
cout << "Hello!";
main2();
return 0;
}
string name = "My name is ______";
int main2() {
cout << name;
return 0;
}
To elaborate on the differences between C++ and Python here: In C++ main is the entry point for your program. So in C++, you can think of the start of the main function as the equivalent of Python's "top of the file". Your program will begin running at the top of main, and stop running at the end of it. Anything that is not invoked starting from the main function (or transitively invoked) will not be executed.
What you wrote is roughly equivalent to the following Python:
def main():
print('Hello')
return 0
name = 'My name is ____'
def main2():
print(name)
return 0
if __name__ == '__main__'
sys.exit(main())
I believe now it's clear why main2 never gets executed: it's never called.
Note that the main function in C++ is the one function which gets called automatically at program start, and exiting main terminates the program. Whatever you want to happen while your program is running must be called from within main.
Also note that a name (such as a function) must be declared before it can be used. So you'll have to either move the definition of main2 before that of main, or at least declare main2 there. Which you could do like this:
#include <iostream>
using namespace std;
int main2();
int main() {
cout << "Hello!";
return main2();
}
string name = "My name is ______";
int main2() {
cout << name;
return 0;
}
You have to call main2() inside main():
#include <iostream>
using namespace std;
string name = "My name is ______";
int main2() {
cout << name;
return 0;
}
int main() {
cout << "Hello!";
main2();
return 0;
}

How to call a function in the main block of code when a prototype is declared

I am working on a code for class that involves performing numerical integration with the trapezoidal rule and discrete data points. Part of the instructions says to call on the function with the prototype:
double trapInt(const double xvals[], const double yvals[], int nElements);
I have already declared the prototype before the "int main" portion of the code but I do not fully understand the exact steps to calling the function.
Note: The code involves using one-dimensional arrays. I also have a PDF of the assignment if seeing that would help.
#include <iostream>
#include <ifstream>
using namespace std;
double trapInt(const double xvals[], const double yvals[], int nElements);
int main()
{
const int MAX_SIZE = 101;
double xData[MAX_SIZE];
double yData[MAX_SIZE];
ifstream infile("trapezoidData.txt");
if(infile.fail())
{
for(int a=0; a<MAX_SIZE; ++a)
{
infile >> xData[a] >> yData[a];
cout << xData[a] << '\t' << yData[a] << endl;
}
}
else
{
cout << "Could not open infile." << endl;
}
cout.setf(ios::fixed);
cout.precision(3);
return 0;
}
Calling a function is very simple. All you do is give the name of the function and put the parameters similarly to how declare the prototype:
main () {
// implementation...
trapInt(xvals, yvals, nElements);
// more implementation...
}
Keep in mind though, just adding this line (or a similar one) to your main function will fail to compile without the implementation:
double trapInt(const double xvals[], const double yvals[], int nElements) {
// implementation of the function...
}
Edit: I originally wanted to leave the calling of the function as an exercise for you, but in the event that you're really in the dark, I'll give you an example:
trapInt(xData, yData, MAX_SIZE);
Just add that line to your main().

How do I get my constructor and functions to work so my main() is able to display both the string and int data?

I am learning about functions and classes, and wrote my own code. I used the constructor to just initialize the variables. I have a function that is supposed to get the info I initialized with the constructor and allow me to display it. However, it doesn't want to work. I am not really sure what I am doing wrong. My error code says that I have unresolved externals because of my "void" function. I thought my function was not returning anything but rather just displaying the input it got from the initialization of the constructor.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
};
void GetBerryInfo (const Berries& B);
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
cout << GetBerryInfo;
system("pause");
return 0;
}
There are several mistakes.
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
should be
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
==================================================================
void GetBerryInfo (const Berries& B);
should be removed.
==================================================================
cout << GetBerryInfo;
should be
Berryinfo1.GetBerryInfo();
==================================================================
All computer langauges are fussy, you have to get the details right, as well as understand the concepts.
This will do what you wanted:
# include <iostream>
# include <iomanip>
# include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
};
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
Berryinfo1.GetBerryInfo();
system("pause");
return 0;
}
A couple of points on your mistakes:
GetBerryInfo() was declared inside the class. You don't need to re-declare it in the global scope. That 2nd declaration should be removed.
To be invoked, functions (like GetBerryInfo) must have () at the end of them like so: GetBerryInfo().
There is no point for GetBerryInfo() to take Berries as a paremeter. It is a member function that is part of the class Berries. It has access to all data members of a Berries instance already.
You don't need to use cout here: cout << GetBerryInfo; because the function body already sends the data members to cout. This function returns void so it doesn't make sense to send this to cout anyway.

Can a header file cooperate with code in main?

I've read that an #include header.h is a preprocessor (because of #), which means it gets processed before compilation.
Is that why my code can't run? Because I'm trying to make an if statement in main with my function from my header(that takes a parameter) and it won't work.
Source.cpp
#include <iostream>
#include "Header.h"
using namespace std;
int main(){
test(46);
if (test() > 30){
cout << "great";
}
else{
cout << "It needs to be higher";
}
system("PAUSE");
return 0;
}
Header.h
using namespace std;
int test(int x){
return x;
}
That isn't the problem. I suspect you might be getting a compiler error message (or linker error) because you have declared test(int x) with an integer parameter and then you call it with no parameter, e.g.: test().
I've modified your code to include an integer result:
int main(){
int result = test(46); // Save the result of calling the function
if (result > 30){ // Test the value of the result
cout << "great";
}
else{
cout << "It needs to be higher";
}
system("PAUSE");
return 0;
}
The test function in Header.h file takes a int as parameter.But in your code you lose it.Pass a int to test function like this.
if (test(42) > 30)
You will get the output: great.

Programming error in C++

I recently started learning C++ but I came across a problem. The program given below is not giving me the desired result as I only see 'Hi' in the result but not what's written in the void function. Please tell me the reason that this is happening along with the solution.
I am using Xcode 6.3.1 and the I have selected the language C++.
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
void ABC ();
return 0;
}
You are redeclaring a void ABC() function inside main(). Just call ABC(); without the void.
You can take a look at this question about declaring a function within the scope of another.
In your code your function call was wrong.
When you call your function you don't need to add the return type:
#include
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC ();
return 0;
}
you need to call your method and not declare it inside main
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}
EDIT 1:
Since you started learning C++ i recommend the following recommendations to make sure your code is cleaner. Please note , these are not rules by any mean , but more of best practices and a style of coding.
Use meaningful names for your variables, methods, functions , classes
... So instead of ABC() name it something that if you (or someone
else is reading it) will now what it suppose to do.
When calling methods and functions try to declare them with the
appropriate returning value. Void by definition doesn't return any
value it just process the code inside of it. so your methods/function
should return appropriate values of do what it suppose to.
Here's version 2 of your code with examples of 3 different methods and calls:
#include <iostream>
using namespace std;
int sum;
string MethodReturningString()
{
return "Hey there i am the result of a method call !";
}
int MethodReturningInt()
{
return 5;
}
void CalculateSum(int x,int y)
{
sum=x+y;
}
int main()
{
cout << MethodReturningString() << endl;
cout << MethodReturningInt() << endl;
cout << "Calculating sum:" ;
CalculateSum(5,4);
cout << sum << endl;
return 0;
}
Happy coding
In C++, like pretty much any other language, you do not specify the return type when calling a function. So change the line that reads:
void ABC ();
to:
ABC();
Try this:
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC();
return 0;
}
You should call a function simply by stating its name and adding parentheses.
instead of using void ABC() for calling the function ABC() in main(), use the following code:
#include
void ABC ()
{
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}