Functions

In funtions in the following example

#include

// Define oscar_wilde_quote() below:

void oscar_wilde_quote() {

std::cout << “The highest, as the lowest, form of criticism is a mode of autobiography.\n”;

}

int main() {

// Call your function here:

oscar_wilde_quote();

}

What happens?What is the use of it?

Instead we can just write

#include

// Define oscar_wilde_quote() below:

int main() {

std::cout << “The highest, as the lowest, form of criticism is a mode of autobiography.\n”;

}
The above will also make the code smaller

Can someone explain what are functions :slight_smile:

Thank You

Hello! Functions are reusable code that can be used many times, by simply saying the function name. In this example, the function is quite long winded, but if you had a longer section of code, checking an input against certain arrays, and then print something out-and if this took 10 lines of code to do, you wouldn’t want to keep writing that out-so, you can write that out once (in a function), then just call the function as many times as you needed.
I hope this helps!

1 Like

Hi @codeneutrino Thanks for replying
I have two questions
Q1)Even if I write the code as follows :

#include

// Define oscar_wilde_quote() below:

void oscar_wilde_quote() {

std::cout << “The highest, as the lowest, form of criticism is a mode of autobiography.\n”;

}

int main() {

// Call your function here:

oscar_wilde_quote();

}
int main1() {

// Call your function here:

oscar_wilde_quote();

}
Here I have written two times but the statement does not get printed twice it is just the same output. You can try by yourself

Q2) ‘the function is quite long winded’ What is the meaning of this sentence

Thank You

Try calling both oscar_wilde_quote() functions within the same main() function.

I meant that the name of the function is quite long, compared to what it does.

Hi @codeneutrino
yes that works but why cant I call it in more than one main function

1 Like

The main function has special properties, if you will, in C++. It shows the program that the code inside it will be executed. Here is some more reading on the subject.

Ok,Thanks a lot.Got It

1 Like