Motivation
Functions
Parameters
Return Values
Default Values
Function Overloading
Think of various functionalities that an application like Youtube might be doing ...
PlayVideo
SignIn
UploadVideo
Like
Comment
Subscribe
...
There are so many actions that a user can do, and with each action there is certain code that needs to be triggered.
Each action requires a function to be executed at code level.
signIn(){
...
}
uploadVideo(){
...
}
recommendVideo(){
...
}
likeVideo(){
...
}
playVideo(){
...
}
A function is a block of instructions which only execute when it is called.
void play_music(){
cout<<"Playing Music";
}
int main(){
play_music(); //call the function
return 0;
}
// Declaration + Definition = Function
void play_music(){
cout << "Enter your favoring song";
int song;
cin >> song;
cout<<"Playing song "<<song;
}
// Declaration + Definition = Function
void play_music(){
cout << "Enter your favoring song";
int song;
cin >> song;
cout<<"Playing song "<<song;
}
play_music();
void play_music(int song_id){
cout<<"Playing song "<<song_id;
}
int main(){
play_music(5);
return 0;
}
You can pass data, known as parameters, into a function. Parameters act as variables inside the function.You can add as many parameters as you want, just separate them with a comma
void play_music(int song1=1,int song2=2,int song3=3){
cout<<"Playing song "<<song1<<song2<<song3;
}
int main(){
play_music(5);
return 0;
}
You can also use a default parameter value, by using the equals sign (=). If we call the function without an argument, it uses the default value.
Functions can also return some data back to the place from where they are called using a 'return' keyword and specifying a return type.
The void keyword, used in the below examples, indicates that the function should not return a value.
void play_music(int song1=1,int song2=2,int song3=3){
cout<<"Playing song "<<song1<<song2<<song3;
}
If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function.
bool login(String username){
// some logic
return true;
}
int countFriends(){
// some logic
return 5;
}
void play_music(int song1=1,int song2=2,int song3=3){
cout<<"Playing song "<<song1<<song2<<song3;
}
When two or more functions, have the same name but different parameters it is known as function overloading.
int area(int side){
return side*side;
}
int area(int l,int r){
return l*r;
}
A call stack is a stack data structure that stores information about the active functions. The main reason for having a call stack is to keep track of the point to which each active function should return control when it completes executing.
int prime(){
...
}
int fact(){
...
}
int main(){
...
}