Function overloading

Posted By: Fenriswolf

Function overloading - 08/20/08 15:51

Hello,

in Lite-C (A7.10.1) function overloading does not work properly when the respective function takes a pointer as an argument (or so it seems; apparently there is a relation).

Here is the thread that led to this conlusion.

Example:

The following code works without any problems:
Code:
int test (char* s);
int test (int n);

void main () {
	int num = 5;
	char* str = "4";
	
	printf("%i", test(num)); //return 5
	printf("%i", test(str)); //return 4
}


int test(char* s) {
	return ((int)str_to_num(s));
}

int test(int n) {
	return n;
}


However, when a pointer is added to the overloaded function as a second argument, overloading doesn't work anymore.
In the following example the first function prototype is always used, leading to a crash. (typecast doesn't help)
Code:
int test (char* s, int *i);
int test (int n,   int *i);

void main () {
	int num = 5;
	char* str = "4";
	
	printf("%i", test(num, NULL)); //return 5 (this will crash)
	printf("%i", test(str, NULL)); //return 4
}


int test(char* s, int *i) {
	return ((int)str_to_num(s));
}

int test(int n, int *i) {
	return n;
}

Posted By: LarryLaffer

Re: Function overloading - 08/20/08 19:19

NULL is an int, not an int*, so you'll need to typecast it

Code:
int test (char* s, int *i);
int test (int n,   int *i);

void main () {
	int num = 5;
	char* str = "4";
	
	printf("%i", test(num, (int*)NULL)); //return 5 (this will crash)
	printf("%i", test(str, (int*)NULL)); //return 4
}


int test(char* s, int *i) {
	return ((int)str_to_num(s));
}

int test(int n, int *i) {
	return n;
}


It's said that the overloading system may get a bit smarter in the feature, but for now, always typecast to avoid problems when you're overloading
Posted By: Joozey

Re: Function overloading - 08/20/08 19:40

So if the engine does not find a matching overloaded function, it takes the very first one?
Posted By: Fenriswolf

Re: Function overloading - 08/20/08 19:45

Yes, you are right; this solves the problem.
In my original example (from the other thread mentioned in the first post) I have to typecast the second parameter to void*.
Thank you for pointing this out, Larry!
Posted By: LarryLaffer

Re: Function overloading - 08/23/08 01:03

Joozey, that's right.

Fenriswolf, np smile I actually run into the same problem a couple of months ago. I was as puzzled as you were in this..

Cheers,
Aris
© 2024 lite-C Forums