0

I am very very VERY new to coding with C++, but I have some experience with Python, and wanted to start to learn functions very early on because I know how much of a lifesaver they can be in the future, can anyone help me figure this out

here is my code

#include <iostream>

using namespace std;
int helloWorld()
{
    cout << "Hello World!" << endl;
    return 0;
}


int main()
{
    int helloWorld;
    return 0;
}
Streylix
  • 9
  • 2
  • 2
    Welcome to StackOverflow! I suggest you to pick a C++ book and start reading from first: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Farbod Ahmadian Aug 27 '20 at 16:03
  • FYI, if your functions don't return a useful value, then use the return type of `void`. For example, in your `main`, you are not using the return value from the `helloWorld` function. – Thomas Matthews Aug 27 '20 at 17:14

1 Answers1

2

In this snippet:

int main()
{
    // Uninitialized variable declaration, no function call
    int helloWorld;
    return 0;
}

You're just simply declaring an uninitialized integer variable, you are not calling the function anywhere.

You need to call it:

int main(void)
{
    helloWorld(); // no need of 'int helloWorld()', 'void' is enough
    return 0;
}
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • It worked! So whenever I call a function I need to have the two ()'s there, and the int isn't needed, in fact it actually messes up the code. Why does it do that? – Streylix Aug 27 '20 at 15:59
  • 1
    @Streylix you defined a variable, which does nothing, instead, you wanted to **call a function()**. – Rohan Bari Aug 27 '20 at 16:02
  • 4
    @Streylix C++ is a *much* too complex and complicated language to learn by trial and error. I suggest you pick up a [good book](https://stackoverflow.com/q/388242/5910058) or two and learn that way instead. – Jesper Juhl Aug 27 '20 at 16:03
  • 1
    @Streylix To amend JesperJuhl's comment, the problem with learning C++ by trial and error is not just its complexity. It is actually not possible because of Undefined Behavior. Errors in your code are not required to produce an easily diagnosed error. Invalid code may compile and execute. The problem is that the behavior is no longer deterministic. There is no way to know if code you wrote is valid, where you can rely on your observations or if it is silently incorrect, where you cannot rely on your observations. You have to already have the knowledge that your code is correct. – François Andrieux Aug 27 '20 at 16:06