|
-
July 15th, 2011, 07:23 PM
#8
Re: Converting a C Program to Compile with C++
 Originally Posted by wdolson
Some functions were defined differently in different files and when compiled in C, they happened by chance to go down the right path to compile OK
In 'C', functions using the same name, but have different parameters are perfectly valid. All 'C' cares about is the name of the function. You can compile all types of junk successfully in 'C' --the issue is that the program created this way exhibits undefined behaviour.
Here is an example:
Code:
int main()
{
int x = sqrt(98, 343, 234324);
}
In the example above, sqrt() is not declared, it takes 3 parameters, and it returns an int. This code compiles and links as 'C' with no errors. When you run it, that's when the weird things happen as the real sqrt() function looks nothing like that. You may get stack corruption errors or other errors.
Some C history -- when 'C' was first introduced, there were no such thing as function prototypes. In other words, you better call the function correctly, including assigning the return value to the correct type, else you would have a compiled program that has huge bugs.
Then came along the idea of the function prototype in 'C' to alleviate this issue. However, 'C' still accepts the stuff I posted above -- you can call any function any way you want (if you haven't declared it with a prototype), with the danger of runtime bugs if you didn't call the function correctly.
but when I switched to CPP, this changed some of the conditionals and things got weird. This was the toughest to untangle.
This is the big difference -- C++ checks prototypes since overloaded functions are valid in C++. If you're taking a C program written without using prototypes for functions, or generally coded by a hard-core C programmer who didn't care one whit about C++, then you will get these issues when converting from C to C++.
I also found some global data declarations that should never have worked at all. The same global data structure was defined in a couple of files. I don't know why this hasn't caused bugs up until now.
See above about what 'C' can do that C++ cannot and was not designed to do.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|