Turning progamers into programmers hell yeah
I wrote up this wall of text while playing EVE. I hope that this thread will become a place where people new to programming can learn what languages are available, how to operate basic parts of programming, get help deciphering inscrutable homework assignments, etc. It might also serve as a useful repository for commonly-asked questions like "what is a pointer", "how do I write a function", etc.
Basic overview
In the code samples here, lines starting with the "#" character are comments. This means that they are not part of the program itself, but are instructions or notes to the reader.
Stuff that doesn't go anywhere specific
Always turn on compiler or interpreter warnings, and set them to maximum. If possible, make them errors rather than warnings. Compiler writers are very smart, and probably know more than you do. Read the documentation to your compiler or interpreter to determine how to set warning and error levels.
Variables
Variables are a way to "label" a certain value. They can be used to reduce code duplication. If you wanted to change the base value in the old code, you would have to update it in three places. In the new code, it only has to be updated in one.
# Old code
value1 = (5 * 10) + 5
value2 = (5 * 10) + 6
value3 = (5 * 10) + 7
# New code
base = 5 * 10
value1 = base + 5
value1 = base + 6
value1 = base + 7
To document code behavior. In the old code, the numbers "5", "10", and "100" are "magic numbers". Their purpose is unknown - may be it's how many cars have been sold, how many employees took the day off sick, or how many dollars were spent on candy bars. May be there's a comment hidden somewhere about its purpose, or may be not. In the new code, their purposes are inherently documented everywhere the variables are used.
# Old code
var = 100
income_today = var * 10 * 0.3
# New code
cent_multiplier = 100
net_dollar_income = 10
tax_rate = 0.3
income_today = net_dollar_income * cent_multiplier * tax_rate
In most modern languages, variables have "types". A type determines what values a variable can hold and what operations you can perform on it. For example, you can add two numbers, but cannot add a number and a string.
Common types of variables:
Boolean - May be either True or False, nothing else. In some primitive languages, such as C, the integers 0 and 1 are used instead of true and false.
Integer - A number with no fractional part.
Floating Point - A number that may contain fractional parts. Because computers only operate on Base 2 numbers, floating point math in most languages can give very "weird" values. For an example, enter "javascript:alert (0.1 + 0.2)" into your browser's URL bar.
String - An ordered list of characters. These might be letters like A, digits like 2, punctuation like !, or "unprintable" control characters such as a "new line" marker.
List - An ordered list of variables. These are usually accessed by a "0-based" index. For example, position 0 of the list (5 10 15 20) is 5, and position 3 is 20.
Conditionals
Conditionals are what separate a programming language from a mere list of equations. A conditional always has an if-block, and sometimes an else-block. In some languages, the two can be combined to save space. One thing to note here is the use of "==" to check for equality. Because "=" is used to assign to a variable, "==" checks if two values are equal.
An example of an if statement:
name = "Alice"
if name == "Alice":
print "Hello Alice!"
else:
if name == "Bob":
print "Guten Tag Bob!"
else:
print "I don't know who you are."
# The same as above, with a combined 'elif' statement
name = "Alice"
if name == "Alice":
print "Hello Alice!"
elif name == "Bob":
print "Guten Tag Bob!"
else:
print "I don't know who you are."
Loops
Loops are used to help reduce code duplication. If you have to do something many times, it's easier to put into a loop than try to write out every step. And if you want to change how many times something happens, it'll
have to be in a loop.
The most basic form of the loop is the while loop. This loop will simply run over and over until some condition is met. If you make a mistake in the body, the loop might run forever and freeze your program.
x = 10
while x < 500:
x = x * 10
print x
The other popular form of the loop is the for loop. A for loop is used for doing something once for every item in a group.
numbers = [5, 10, 15, 20, 25, 30]
# The number is: 5
# The number is: 10
# etc
for number in numbers:
print "The number is: ", number
# The name is: Alice
# The name is: Bob
# etc
for name in ["Alice", "Bob", "Charlie", "David", "Eve"]:
print "The name is: ", name
Posts
I prefer OCaml. Its got a couple of things going for it, but the big one is that there are fewer hoops to jump through if you want to compile it to native code. Hell, you can even set up profiling flags for it. Plus its got some nice hooks into GTK and other super-useful libraries, which helps a lot. Native object support, which I think lisp has, but I never really got the hang of it.
But again, unless you're major avenue of development is... well artificial intelligence research of some sort, planning, search, linguistics, that sort of thing, I can't imagine why you'd be using a functional language outside of the language concepts courses you have to take along the way to a degree.
F# :lol:
I'm a CLR whore.
It is an ML family language. It is very similar to OCaml.
I don't know of any syntax highlighters that will output BBCode, and it would feel silly to just screenshot my editor and post it inline. The default forum highlighting also sucks.
I never understood the difficulty learning recursion, so I figured I'd just use the simplest possible version and let people figure it out. If anybody expresses confusion I'll try to add more detail (or, if somebody writes more detail I'll edit the OP to include it).
If you, or anybody has improvements they'd like to see in the OP, write them and I'll edit them in.
Whoooooooops. I had originally intended to demonstrate map(), but that would have required introducing mutable lists, so I just changed to an exists() example without changing the name. Will fix.
Nano has syntax highlighting.
jQuery also makes Javascript reasonable to deal with in general. An example with the humble for loop:
/* No jQuery. getElementsByClass does not actually exist, but inventing it makes this example much easier to read. */ var elements = document.getElementByClass ("my_class") for (var index = 0; index < elements.length; index = index + 1) { var element = elements[index] alert ("Got an element") } /* With jQuery */ $(".my_class").each (function (index, element) { alert ("Got an element") })I have no idea how I missed that. That is truly wonderful - thanks!
I've never been able to find a good source for this sort of thing either, so I mostly just imitated existing projects that were similar to whatever I was writing. For a game, you could poke around in the Quake 3 source code and see how event handling is implemented. Or were you referring to the actual layout of files and directories?
They're handy for passing variables by reference to functions, rather than by value. There's probably some situation where that's useful.
They're not quite as vital in C++ as they are in C, because you can use references and classes with copy constructors to emulate them. However, having to copy data all over the place is much slower than just passing around a few pointers.
In C, they are mandatory for returning any sort of complex data or maintaining relationships between data. Just try to implement a linked list without pointers.
It's usually just an efficiency thing in C++. In some cases, if you aren't one of those people who thinks that every piece of your program needs to be an object no matter what, it's a lot simpler to pass a pointer than it is to write a class. Sometimes it's necessary, but not often. Even so, you can do some pretty neat stuff with pointers if you understand them well enough, so it's not something you should just brush off.
It's also a great thing to understand, because you never know when you'll have to use a language that uses pointers or something similar on a regular basis. I'm in a class now on IBM mainframe assembly language and if I didn't already understand pointers from C/C++ it would be a hell of a lot more difficult to comprehend what the fuck I'm doing when I'm trying to pass around memory addresses as parameters so I can change specifically declared parts of storage.
Dynamic memory allocation. You aren't always going to know at compile time how big an array needs to be or how many instances of a class you'll end up having, and pointers let you create them on the heap as needed.
Multiple references to the same object. Many times different parts of your code will need to maintain references to the same object(s). If you tried to do this by copying the object in question, not only would you have to deal with potentially expensive copying (particularly for instances of classes with lots of data members), but the copies would drop out of sync with each other as soon as one of them was modified. Pointers are not only much smaller, but refer to the same actual object/variable, ensuring any changes are reflected immediately everywhere.
Argument passing. Explained in the posts before mine, so I won't get into it.
Arrays. The name of an array is really a pointer to the beginning of the location in memory where the array is stored. For example, array[1] is equivalent to *(array + 1).
Function pointers. This is a little more advanced/esoteric, but you can write code that calls a function determined at run time. I'm not sure how often this is strictly necessary, but the alternatives are things like switch statements with potentially long lists of cases, and function pointers can simplify things tremendously.
It can be nice even with objects, if the object in question allocates a lot of data. Say you have an Image object that stores decompressed RGB data. You could just return an instance and use the copy constructor, or use new and return the pointer. The former would be unusably slow, the latter would be almost instant.
When dealing with that sort of situation, there really aren't that many instances (actually, I can't think of any off the top of my head) where you couldn't use a pointer instead of a normal variable. Dynamic data doesn't take up any more space than static data, so when dealing with classes you're probably better off just using pointers for everything that doesn't absolutely need to be static.
Pointers can be a pain because they don't work with RAII, which depends on using stack-based variables. Without RAII you're back to the bad old days of manually checking error conditions, deleting allocated memory, and trying not to leak.
Sorry, I diverged a bit there. What beginners really need to know is how various languages deal with multiple source files. The latter question (about designing my game) is really separate and stems from some current brain hurt I am experiencing trying to sanely architect my current project (which is a Python/pygame-based roguelike, and I already have a topic on it in H&A). And yes, I have indeed poked around in the Q3 source, but it's no help for me currently since an FPS has wholly different design requirements from a roguelike.
How can RAII work in the context of C++ though, unless that language, unbeknownst to me, allows for the efficient passing of object references like java? It seems useful here and there, but an impossible ideal to achieve thanks to how C++ is designed.
Ah, OK.
Python has modules and packages. A module is a single source file ending in .py. A package is a directory containing multiple .py files and an __init__.py file. From the perspective of the file doing the import, these look the same. Most dynamic languages do not require compilation and thus follow this pattern. Some have an equivalent to __init__.py, some do not.
C and C++ have header and source files. A header file acts as a description of all the public capabilities available in the source file. Source files are compiled into machine code, and then linked together (using the headers as a guide) to create a final executable. When headers are included, they are actually copied into the file they are included in. If you pre-process a file that imports the standard libraries, the file might be hundreds of thousands of lines long. This is part of the reason that C and C++ compilers are so slow - they must re-parse the same text hundreds or thousands of times.
Java and C# are similar to Python, except their modules must be compiled before use (into .class or .dll). They also have no equivalent to the __init__.py file, so you can't re-arrange the contents of the packages at runtime.
PHP textually inserts included files, just like C or C++. However, because it's not compiled, the actual source code files are imported rather than headers.
Javascript has no import or include functionality, so you must keep track of a script's dependencies and include all of them in the HTML source code.
You can pass references by prefixing a function's parameter with the "&" symbol. It should be noted that Java references are very different from C++ references.
// Java code void my_func (int var) { var = 6; System.out.println (var); } // Prints 5 6 5 int my_var = 5; System.out.println (my_var); my_func (my_var); System.out.println (my_var); // C++, no references, var is copied void my_func (int var) { var = 6; std::cout << var << std::endl; } // Prints 5 6 5 int my_var = 5; std::cout << my_varvar << std::endl; my_func (my_var); std::cout << my_varvar << std::endl; // C++, references, var is not copied, assignment statements apply to the actual variable. void my_func (int &var) { var = 6; std::cout << var << std::endl; } // Prints 5 6 6 int my_var = 5; std::cout << my_varvar << std::endl; my_func (my_var); std::cout << my_varvar << std::endl;Also, pointers allow you to practice a form of polymorphism when dealing with base classes and subclasses.
For example:
class A { public: virtual void SomeMethod() { } void SomeMethod2() { } }; class B : public A { public: virtual void SomeMethod() { } }; void main() { A* PointerToA = new A(); // PointerToA now points to an instance of the A class PointerToA->SomeMethod(); // Executes member method of A class delete PointerToA; // Free memory to stop the leakage PointerToA = new B(); // ZOMG WTF?! Variable now points to an instance of the B class. You can only do this with inheritance PointerToA->SomeMethod(); // This actually calls the method as defined in B, not A. PointerToA doesn't actually have to know what class it's pointing to, as long as it's A or some class derived from it delete PointerToA; return; }Another example:
class A { public: virtual void SomeMethod() { } void SomeMethod2() { } }; class B : public A { public: virtual void SomeMethod() { } }; void PointerWork(const A* InputPointer) { InputPointer->SomeMethod(); } void main() { A* PointerToA = new B(); PointerWork(PointerToA); delete PointerToA; return; }Here, PointerWork doesn't know beforehand that it's actually getting an instance of class B. It actually doesn't have to know that class B exists at all. So long as a class is derived from A somewhere (it might be derived from a class derived from A), it's perfectly valid. You can accomplish the same in languages such as C# with references, but in C++, you use pointers.
I have dev-c++ downloaded. I really don't know how it works and have some introduction to programming guides I plan on reading. But since I haven't even gotten my feet wet, is that a good place to start (I want to eventually make games)?
In essence. If your code is all server side, you don't need it.
Podcast 0207: Sinking to new depths
Preview: Is Uncharted: Golden Abyss the Vita’s killer launch title?
Dynasty Warriors: Gundam 3: Macro-wreckonomics
Dev-C++ hasn't seen an update in years.
http://forums.codeblocks.org/index.php?board=20.0
Indeed. Code::Blocks is pretty much the heir to Dev-C++. Hell, it even supports Dev-C++ project files!
Sweet. Thanks guys.
You should be aware that CodeBlocks doesn't actually provide its own compiler, it's JUST an IDE. However, if you have Dev-C++ installed, it should pick up the compiler it has and use it.
Also, if you like there's always Visual C++ .Net 2005 Express, which is free from MS with a valid version of Windows. I personally don't like it (though I DO like the C# IDE, and I think it's strange that it's so much better) and use .Net 2003 which I got through my school, but it's adequate and beggars can be choosers.
Switching gears, here's a little program I made in C# as part of Gamedev.net's C# workshop.
Program
Source File 1
Source File 2
Why would you be using .NET 2003? It's free.
Go download 2005, or 2008 if you feel like being a lab rat.
People are so picky these days.
I know it's free. But see, here's the thing, I just don't like how C++ 2005 Express operates, while 2003 doesn't piss me off near as bad. C# 2005 is fine. Also, my version of 2003 is the standard edition, which means I get cool things with it like the GUI designer, which is pretty handy when dealing with Win32.
VC++.net 2005 express comes with a GUI designer as far as I know. All the other expresses do, so it seems logical.
What do you mean by "GUI designer?" Express Edition has basically the same visual form designer that other editions have.
I use Visual Studios 2003 Enterprise Developer at work and the various Express Editions at home. There aren't many times that I run into things that I need that are missing. Add-ons and conditional break points would be nice. The express editions don't have as many project types, but usually that just means you have to go into options and change a setting or write a line or two of code to get the same effect. It is worth it to get generics and anonymous delegates and LINQ and whatever that feature is called where you create a static method that takes an instance of some type and some other arguments, and then allows you to call it as if it were an instance method of that type that you passed in.
[edit]
Crap, you are talking about C++ and I am talking about C#. C++ is the only Express Edition I haven't installed. Several of the CS courses I took used C++, but damn I wouldn't want to use it day to day. If you know what you are doing in C# you can usually get >90% of the performance for a fraction of the effort. I say usually because a C# program could never get anywhere near 90% of the performance of FFTW, but that is what P/Invoke is for. Here is a good example.
They come with a designer for Windows Forms, but not Win32, and I'm pretty sure C++ comes with neither. Even if it did have Forms, if I were using Forms, I'd be in C# anyway.
Added: I should note that it's actually not mostly a matter of features. Fact is, I rarely use Win32 anyway. There's just something in the feel of it that annoys me, and is only present in VC++.net 2005. VC#.net 2005 doesn't suffer from this oddly enough.
Added again: just tried the 2008 beta, as it occured to me that I hadn't messed with it yet. Same problems, though I appreciate them loading it up with Win32 stuff on install, rather than having to install other stuff as well as modifying the template files to get first class support going. Still no designer though.
jackal: Ah, yeah, easy mistake to make. I actually really like the C# express edition, I think it works really well. What I hate the most about the C++ version is the build output window. It doesn't make it easy to find errors in that mass of output at all. I don't understand why they did it like they did- the C# version is great, and is identical to the 2003 editor. It confuses me greatly.
Also, I usually code in C#, but often times C++ is needed when working with some specific API that doesn't have .Net bindings. I work in C# when I can, but C++ will always always get the job done.
Lists are cool and all, but not when I just need a mass of data of a fixed size that has to be accessed very quickly and is also mutable (unlike a tuple).
Specifically, my roguelike calls for a ton of 2D arrays. I have a 2D array of tiles in the current map. My display class needs an array of tile-to-screen mappings to avoid doing lots of repeated multiplication to place tiles on the right pixels (actually I suppose that wouldn't be much faster, if at all, but I thought of this idea and dammit it seems like a good one). I need to iterate through these with "for" loops. If Python has an equivalent way of implementing this kind of thing that's not horribly inefficient, I haven't found it.
Also, I've looked at Numeric some, and I don't need arrays of numbers - I need arrays of objects.
T-shirts | Last.fm | Flickr | dA
As far as I know, it's because C++ isn't actually supported out of the box, and relies on a plugin that's not actually done yet.
However, whenever someone breaths Java, Eclipse is always shouted pretty loudly.
The same reason people don't seem to like Blender or The GIMP. They're excellent programs with many strengths, but there is a minor learning curve on the interface.
I didn't like Eclipse's interface, but that was a first impression, and I haven't had any incentive to try it since Code::Blocks works for me.
You could try using list comprehensions, I've found those to be faster than for loops in general. However, to get near-C performance in Python you'll want to take a look at a library like Pyrex.
However, the speed benefit of moving to compiled modules in C is likely to be much less than what you could gain by simply using a more efficient algorithm.
Interesting. Code::Blocks handles Java or does Eclipse handle C/C++? Either way, color me surprised, because I thought the former was mostly for C/C++ and the latter was Java. I'm a NetBeans guy, myself.
Wow, that last sentence makes me sound like a fairy.