Please read the new rule regarding the restriction on the use of AI tools. ×

C++/C initializing with a value in Function!!

Revision en2, by rishabh007, 2020-01-01 21:38:48

While reading about Finding Bridges in a Graph I came across an article Article link on a website. I was amazed that void dfs(int v, int p = -1) {.....} In the code there were two types of function call 1) dfs(to, v); 2) dfs(i); I thought this might give a wrong answer but both of them were working. When nothing was passed the value of p was -1 and when a value was passed p took that value.

#include <iostream>
using namespace std;
void dfs(int p=-1)
{
	printf("%d",p);
}

int main() {
	int a=5;
	dfs(a);
	return 0;
}

Output: 5 Now the second case.

#include <iostream>
using namespace std;
void dfs(int p=-1)
{
	printf("%d",p);
}
int main() {
	
	dfs();
	return 0;
}

Output:-1 Amazed!! So this feature can be used when like starting of recursive calls when there is no parent for the source but after that, each node has a parent. You can read about it and the ambiguity associated with it. Default arguments PS: This is my first blog. Support if you find it useful or comment out for any improvement.

Tags #function calls, #reference-variables, #bridges, #graph

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English rishabh007 2020-01-01 21:38:48 132
en1 English rishabh007 2020-01-01 21:11:05 1166 Initial revision (published)