Jump to content
  • Advertisement
Sign in to follow this  
Markie

Moving from PHP to C and C++

This topic is 4029 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, I've done some PHP programming in the past and now I want to get in really deep with game programming, so C and C++ are on the menu for rest of my life. ;-) Since I got quite accustomed to PHP and still need it for my web-apps, I keep forgetting the differences between PHP and C (and C++) because it's such a long haul from READING books on C anc C++ to actually USING it for an own windows game. Long text made short: Are there any resources that quickly point out the differences between PHP and C and how to work around them? For instance, it seems in C there are no associative arrays and the length of arrays (and strings = character arrays) can't be changed on the fly like in PHP. Has anyone assembled a list of such differences and how to work around them in C? I just want to get into a "productive" phase of using C as fast as possible so I don't keep forgetting. And if I do, to have some reminders how to get back into C from PHP. Regards, Mark Edit: Thanx, Mod for deleting my accidental double post. - Sorry.

Share this post


Link to post
Share on other sites
Advertisement
C and C++ are distinct languages with distinct philosophies. There's a lot of differences between the three. The main ones would be, IMO:

  • Build process.

    PHP is interpreted: the code is executed directly without any other work.

    C and C++ have a two-step build process. Compiling reads every translation unit (each source file and the header files it includes) and builds an object file representing all the entities used by that translation unit (functions, globals, classes) and all the entities defined by that translation unit (functions, globals, classes). Linking reads all the object files and matches the "used entities" with the "defined entities" to build the entire program. Also, unlike PHP, neither C nor C++ allow code at file scope: only definitions and declarations.

  • Declaration.

    In PHP, you need to define functions and classes before you execute code that calls them. However, code that uses a given function or class may appear before code that defines it, as long as it's not executed (for instance, it's inside a function).

    In C and C++, you still have to define functions that you call, but you also have to declare them above the point in code where they are called, regardless of the order they are called in. This means explaining to the compiler what the objects are through means of either a definition or a forward declaration (useful when dealing with mutually recursive symbols).

  • Resource Ownership.

    In PHP, memory is handled by the interpreter and freed whenever you don't need it anymore. The same holds for most resources (MySQL results, open files, GD images etc) that will be blasted at the end of script execution.

    In C, resources are divided into static memory, auto memory, dynamic memory and external handles. Static memory remains alive for the duration of the program. Auto memory is automatically destroyed by the compiler at a fixed point, that may happen before you actually wanted it to be destroyed. For instance, any auto objects created in a function will be destroyed before that function returns, so you'll have to resort to returning a copy. Dynamic memory and external handles are created through a function call, and remain yours until you manually release them with the appropriate function. If you forget, you leak the resource (and so your program may run out of available resources sooner or later), and if you do it too soon your next interaction with the resource will cause strange stuff to happen.

    C++ adds the concept of ownership managers: these are classes that will handle the release of external handles and dynamic memory for you. Typical examples are the smart pointers (std::auto_ptr, boost::shared_ptr) and containers (std::vector). It's very unusual for a C++ program to release dynamic memory manually.

  • Safety.

    PHP is more-or-less sandboxed. Incorrect operations are detected and issue a warning, or may even stop the program. Almost all operations in PHP have a cleanly defined behaviour. On the other hand, there are very little ways to guarantee that a given PHP program will not do stupid errors, such as using a string where an array was needed, or defining a function before calling it, without thoroughly testing the script.

    C and C++ are statically typed languages, which means that the type of variables and functions is checked at compile-time, which prevents using a string where an associative array was needed or similar issues. C++ has improved type-safety over C, which must rely on unsafe void* or varargs manipulation where C++ can use inheritance, operator chaining or templates. However, C and C++ contain a lot of undefined behaviour: things which are detected neither by the runtime nor by the compiler and will result in unexpected situations that are most of the time quite incorrect. For instance, accessing dynamic memory after you've released it will behave randomly: it might work one day and crash the program in a random and faraway location the next, or produce spurious results that vanish when you attempt to debug the program.

    As a consequence of static type-checking, C++ supports overloading: several functions with the same name may be used, provided they all take distinct argument types. Obviously, neither C nor C++ may have arrays of "mixed" values. You can have an array of integers, an array of strings, but not an array of "strings or integers".

  • Containers, strings.

    PHP provides native string, array and dictionary entities, all of which are resizable and garbage-collected, and are first-class citizens (you may use them as any other value in PHP).

    C provides a native array type, which is a second-class citizen (it may not be passed as an argument to a function, or be returned by a function), is not resizable, and does not have a count equivalent. Because of this, it's seldom used except to hold hard-coded data. Instead, pointers are used. They are not resizable and have no count equivalent, but at least they're first-class citizens so they can be passed around (provided that you manage the underlying memory yourself, as it may be static, auto or dynamic and these imply very different strategies). C provides a native string literal approach, along with a definition of strings as a "buffer of characters containing a NUL character". The string value itself is stored in that buffer starting at the first character and until the first NUL character excluded. So, strings are resizable (by moving the NUL character forward) so long as you don't exceed the size of the underlying buffer (so you have to manipulate underlying buffers every time you manipulate strings). C provides no native dictionary type.

    C++ provides std::vector, which is a first-class citizen, resizable array, and provides a .size member akin to count. You may pass it to functions (by copy or reference, as in PHP) and return it from there (by copy only if it's an auto variable). It also provides std::string, which is a first-class citizen, resizable string also with a .size() member, which handles its underlying buffer itself (so you can use them as if they were PHP strings). It provides std::map (and, soon, a hashtable) which is a dictionary that assumes its keys are ordered (integers, strings, or whatever comparable type you can come up with).

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
C and C++ are distinct languages with distinct philosophies. There's a lot of differences between the three. The main ones would be, IMO:
<snip>

Wow man!
Did you write all that just now?
You're blowing me away man!
Thanks!

I didn't expect anyone to write a full list like this in response, I was just hoping for some pointers (links) to resources and documents on the net.
Thanks for your thoughts! I understand about half of it at this point...
;-) (Not because you're not expressing yourself clearly, just because I havn't heard of a lot of the things you mention.)

Generally I'm having a little bit a hard time with this switch because PHP is so much more "user friendly". Switching from PHP to C or C++ feels a little like switching from using Window$ to LinuX... ;-)
It just makes you *cry* out for HELP! ;-)

In this manner I was just kind of hoping for some kind of tutorial how to do stuff in C and C++ which is easy in PHP but not native in C (like adding any number of characters / strings to an existing string on the fly, etc.).
But your general thoughts are certainly a good foundation and starting point to outline the foundational differences! Perhaps some more people who know all 3 languages or even made the switch from PHP to C and C++ in the same order as I might also comment.

Thanks again,
Mark

Share this post


Link to post
Share on other sites
Well, it looks like ToohrVyk has already said everything you should know, but I'll add my grain of sand:

Remember that PHP is based on C, and not vice versa. PHP uses the same syntax of the control structures and loops, but the very purpose of each one is quite different.

I've worked extensively with DHTML languages, and in every case (PHP, VBScript, javascript) the web version is simplified a lot compared to its general purpose counterpart. This simplification is given in the use of variables and strings (mostly). Since you don't have to mess with memory management or thread optimizations, these aspects are removed altogether in the web version.

So, basically, your PHP knowledge serves as a good basis for you to start learning C/C++ from a SYNTAX viewpoint, but the API (C/C++ standard libraries) shall be an entirely new ground for you to explore.

But don't worry!! You have already given the hardest step (the first). Begin experimenting as soon as possible, and do not hesitate in posting another thread if you get stuck or need any further advice.

But, before you post a question, ask Dr-Know (a.k.a. Google), you'll centainly find lots of pages with help and tutorials, and it's almost certain that any question you happen to encounter, someone else did as well and has already solved it.

For now, I'll recomend you and excellent site:

C++ reference

There you'll find extensive and comprehensive tutorials and full C/C++ standard libraries reference.

PM me if you get stuck, and rate me if you want to!

Share this post


Link to post
Share on other sites
Quote:
Original post by Fighterguard

For now, I'll recomend you and excellent site:

C++ reference

There you'll find extensive and comprehensive tutorials and full C/C++ standard libraries reference.


Also bookmark Cppreference, another excellent site as strictly a reference for the language.

Share this post


Link to post
Share on other sites
Quote:
Original post by Fighterguard
<snip>
So, basically, your PHP knowledge serves as a good basis for you to start learning C/C++ from a SYNTAX viewpoint, but the API (C/C++ standard libraries) shall be an entirely new ground for you to explore.

But don't worry!! You have already given the hardest step (the first). Begin experimenting as soon as possible, and do not hesitate in posting another thread if you get stuck or need any further advice.
<snip>


Thanks a lot for your encouragement! :-)
You're right, experimenting is one of the most important aspects when learning a new programming language. If you don't experiment, you'll keep forgetting what you've just read. In fact, you will want to never stop experimenting (programming) so you will never forget again!
- I'll stay at it! :-)

And thanks to you and Phantoms for the recommended sites!
(And yes, I've rated you up, for whatever that's good for. ;-)

Regards,
Mark

Share this post


Link to post
Share on other sites
Mark, if you're interested in printing out the Cppreference site to keep in a binder as a reference, I just finished putting it into PDF format with TOC bookmarks and Nate at cppreference has made it available in the download section of the FAQ (http://cppreference.com/faq.html).

It's available as two PDFs, the C/C++ Reference and the STL Reference. If you intend to print it out, be aware they are both about 180 pages each. But it's worth it to have a printed reference.

Share this post


Link to post
Share on other sites
Get yourself a book and work through the example code - reading alone you won't understand as well.

"C++ from the Ground Up" is a good one - by Herbert Schildt.

Share this post


Link to post
Share on other sites
The more I do PHP the more I miss object oriented C++. Unfortunately my new job will have me using PHP 4.9. There are no objects in PHP 4.9 :(

Anyway, I would say that C++ lends itself better to good structure OO programing while leaving plenty of room for procedural stuff when needed. C++ is powerful and complex with many counter-intuitive pit falls. I would suggest the Scott Meyer's books "Effective C++", and "More Effective C++" after you have gotten used to the C++ syntax. Those books have a lot of stuff I never would have figured out on my own.

Also, please do not mix up C with C++. C in my eyes is a hideous beast only to be used only in the ugliest of situations. Ok, its good for programs that are less 1000 lines of original code. Anything more and I'd advise some OOP.

Either way, C++ is not C and if you are using C++ you should be using the STL and you should strongly consider boost. The learning curve is sharp, but once you get a hang of it, C++ is a very beautiful tool.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!