Tuesday, February 14, 2006

How does it work

int main()
{
return(mycmp("a"));
}
int mycmp(char * a1,char *a2)
{
printf("mycmp called");
return(1);
}


$>cc mystring.c
$>./a.out
mycmp called
$>

How is mycmp called when the parameters are different.

7 comments:

Arvind said...

http://www.programmersheaven.com/2/Calling-conventions
The above link might explain the answer. In brief, the 2nd argument is initialised to NULL and passed to the function. Hence no errors are generated. And the code works fine.

Shantanu said...

There are 2 questions to be answered here
1) Why is the compiler not throwing error when mycmp is undeclared in its call in main?

2)Why is the fucntion called with NULL/Junk arguments?

Shantanu said...

Additional observations
/* Code below has the following
1) No compiler error
2) Check which function is picked up
*/
int main()
{
return(mycmp("a"));
}

int mycomp(char * a1)
{
printf("Should be called a1=%s ",a1);
return(1);
}

int mycmp(char * a1,char *a2)
{
printf("Should not be called a1=%s \t a2=%s",a1,a2);
return(1);
}

Shantanu said...

Just rename the above code from *.C and *.CPP and compile.

peace restores

Unknown said...

Function is not declared. So, in C, the function is assumed to take an arbitrary number of arguments and return an int. So, that works fine. C++ would complain about a missing function prototype.

Murali said...

How do i become a contributor to this blog ?

Shantanu said...

Give me ur mail ID