Our new Indie Games subforum is now open for business in G&T. Go and check it out, you might land a code for a free game. If you're developing an indie game and want to post about it, follow these directions. If you don't, he'll break your legs! Hahaha! Seriously though.
Our rules have been updated and given their own forum. Go and look at them! They are nice, and there may be new ones that you didn't know about! Hooray for rules! Hooray for The System! Hooray for Conforming!

The beginner programming thread

JaninJanin Registered User
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

Janin on
[SIGPIC][/SIGPIC]
«13456763

Posts

  • JaninJanin Registered User
    edited November 2007
    Functions

    Functions are another tool for reducing duplicated code (see the pattern yet?). Just like a function in mathematics, a programming function takes some variables as input and returns some as output. Unlike mathematical functions, programming functions can do other things as well, such as save files or send stuff to the user. A function will run until it reaches a "return" statement, at which point it will give control of the program back to the parent function.

    Basic functions

    I'll define a simple function here, so you can see how it's put together. As an example I will use the Fibonacci function, which is defined thus:
    470072226d1629b5b6b973f1881b2051.png
    def fib (n):
    	if n == 0:
    		return 0
    	if n == 1:
    		return 1
    	return fib (n - 1) + fib (n - 2)
    

    Keyword parameters

    Some languages support a concept known as "keyword parameters", which makes it easier to remember what goes where if the function has many parameters. An example using the income_today example from earlier:
    def income_today (net_dollar_income, tax_rate):
    	cent_multiplier = 100
    	return net_dollar_income * cent_multiplier * tax_rate
    
    print income_today (net_dollar_income = 10, tax_rate = 0.3)
    

    Functions as parameters

    As one last functional feature, some languages support functions as parameters! These are fun. I'll use an example of searching a list for a value that matches the passed in function. This code sample will check if a list of names contains "Alice" or "Bob".
    def matcher (x):
    	if (x == "Alice") or (x == "Bob"):
    		return True
    	return False
    	
    def exists_in (list, match_func):
    	for item in list:
    		if match_func (item):
    			return True
    	return False
    	
    # Prints "True"
    print exists_in (["Alice", "Charlie", "David"], matcher)
    
    # Prints "False"
    print exists_in (["Charlie", "David", "Eve"], matcher)
    

    [SIGPIC][/SIGPIC]
  • JaninJanin Registered User
    edited November 2007
    Types of languages

    Languages are broadly split into two categories, dynamic and static. A static language has types fixed when it's run. If a function in a static language expects to get an integer, you can't pass it a float instead. For this guide, I will be focusing on dynamic languages, because I find them easier to read, write, and maintain. Specifically, I will cover Python (my personal favorite), with a small detour into Javascript.

    Dynamic languages

    An incomplete list of popular dynamic languages:
    Python - Popular for everything from game scripting (Battlefield 2, Civilization 4) to web applications to physics simulations. My personal favorite.
    Ruby - A less well-known language than Python, Ruby has seen a resurgence with the advent of Rails, a popular web application development framework.
    Lisp - A somewhat popular language following the "functional" paradigm, the basis for programs such as GNU Emacs and...uh...
    Smalltalk - Still one of the best object-oriented languages around. Many of the ideas in Smalltalk were used in Objective C, which forms the basis for much of OS X.
    Perl - Very popular for UNIX scripting, but is infamous for being rather easy to make incomprehensible.
    ECMAScript/Javascript - The most popular and widely installed language on the planet. Has gained a reputation as a horribly awful language due to incompetant monkeys writing in it, but in reality it's only moderatly awful.

    Python
    One of the most popular dynamic languages, used for everything from large websites like Google to game scripting. All data is modeled as "dictionaries" -- otherwise known as "associative arrays" or "hash tables" in other languages. Objects, modules, and full libraries are simply dictionaries of attributes. Python is also a philosophy -- well-written code is said to be "Pythonic" if it obeys the Python philosophy, which emphasizes explicit behavior and "one obvious way to do it". Python is said to be "batteries included", and features a massive standard library.

    Ruby
    Borrows the good ideas from Perl, Smalltalk, and Lisp. All data is contained in objects, and all objects communicate by passing around "messages". Message passing is the distinguishing characteristic of Ruby and Smalltalk. It allows very flexible programming by making a class responsible for *all* of its behavior. Want to set the "bar" attribute of object "foo"? When you execute "foo.bar = 1", you're actually performing "foo.bar= (1)". No modifications to an objects state are permitted except through its messages.

    ECMAScript/Javascript
    Crazy shit, "some text" + 10 = "some text10" instead of an error. Use a library like jQuery or you will go mad.

    Static languages

    Rather than try to describe all the differences between dynamic and static languages all at once, here's an example of printing out names from earlier. Keep in mind that both versions are the full program:
    #include <stdio.h>
    
    #define NAME_COUNT 5
    
    int
    main ()
    {
    	char *names[NAME_COUNT] = {"Alice", "Bob", "Charlie", "David", "Eve"};
    	for (int index = 0; index < NAME_COUNT; index = index + 1)
    	{
    		char *name = names[index];
    		printf ("The name is: &#37;s\n", name);
    	}
    	
    	return 0;
    }
    

    There are several things to notice here:
    - The definition of the main() function. A static language such as C requires that all code be placed in functions. In practice you will rarely write code outside of a function in any language, but it can be helpful for learning how to program.
    - The code uses an array, rather than a list. The nuances of arrays are discussed in a following post.
    - The for loop is dramatically different. Rather than simply passing each value into the block, the user must manually construct, check, and update an index variable.
    - The print function requires that the user specify what is being printed (a string, "%s"). If you specify an incorrect type code, the program is likely to crash.

    For this reason, I do not advise new programmers to immediately jump into using languages such as C/C++/C#/Java. When you've learned how to walk, then you can learn how to walk in lead boots. I especially ask that you do not start with any dialect of Basic, because the available good example code is dwarfed by the amount of bug-riddled, insecure garbage.

    [SIGPIC][/SIGPIC]
  • JaninJanin Registered User
    edited November 2007
    This page is TODO because OOP is a big subject and I wanted to get the rest up first.

    EDIT: I've added some more to this, but I'm really lazy and OOP is a big subject.

    Object-oriented Programming

    The two core principles of object-oriented design are information hiding and behavior sharing. Rather than a mass of single-purpose functions, bundle them together to provide a clean interface for the rest of the code to access.

    Information hiding

    Just as a function protects other code from having to know what operations it goes through to arrive at a conclusion, OOP protects other code from knowing what function is being called and what data is being used. If you create an object with certain data and then pass it to a function, the function does not know and does not need to know what data the object was created with. The object can be treated as a magic black box that spits out answers. If you use a functional language like Haskell or Lisp, closures provide much the same function.

    It also allows for sane state management - rather than a giant grab-bag of global variables that might get modified who-knows-where, the object's variables are protected from unknown modifications. This can come in very handy during debugging, when you need to know when a data value is (for example) being set to something invalid. If it's a global, you would have to put print statements all over the place or trust in a debugger. If you use an object, you can put in many less statements (or breakpoints, whatever). Obviously, the closer access to an attribute is controlled within the object, the fewer "chokepoints" there will be for the data.

    Note that this does not mean that you should hide all attributes behind get_ functions. I see this annoying pattern a lot in Java programmers, because they've had OOP slammed down their throats in a language that doesn't support properties. If the purpose of your class is to simply contain a bunch of data with no behavior, just make all the attributes public. Please do not ever write classes that look like this (might not compile, been a while since I used Java, but you get the idea):
    /**** DO NOT DO THIS, DO NOT DO THIS, DO NOT DO THIS ****/
    class DataContainer {
    	private final int a, b, c, d;
    	public DataContainer (int _a, int _b, int _c, int _d)
    	{
    		a = _a;
    		b = _b;
    		c = _c;
    		d = _d;
    	}
    	
    	int get_a () { return a; }
    	int get_b () { return b; }
    	int get_c () { return c; }
    	int get_d () { return d; }
    }
    /**** DO NOT DO THIS, DO NOT DO THIS, DO NOT DO THIS ****/
    

    Behavior Sharing

    Say you've got two classes for printing that share some of code, but have parts that are different:


    By moving the common code into a shared parent class, you can reduce code duplication. This is probably easiest to see with an example, so I'll use a hypothetical printing library. This library can handle both laser printers and ink printers:
    class LaserPrinter:
    	method calculate_size ():
    		size = 10
    		
    	method print ():
    		calculate_size ()
    		feed_paper ()
    		check_toner_level ()
    		warm_up_laser ()
    		fancy_laser_stuff ()
    		check_supplies ()
    		warn_on_low_supplies ()
    		
    class InkPrinter:
    	method calculate_size ():
    		size = 10
    		
    	method print ():
    		calculate_size ()
    		feed_paper ()
    		fancy_ink_stuff ()
    		clean_excess_ink ()
    		check_supplies ()
    		warn_on_low_supplies ()
    		
    

    Note the duplicated code. This problem can be reduced if you move the common code into a parent class, and then inherit from it:
    class Printer:
    	method calculate_size ():
    		size = 10
    		
    	method print ():	
    		calculate_size ()
    		feed_paper ()
    		fancy_parts ()
    		check_supplies ()
    		warn_on_low_supplies ()
    		
    class LaserPrinter (Printer):
    	method fancy_parts ():
    		check_toner_level ()
    		warm_up_laser ()
    		fancy_laser_stuff ()
    		
    
    class InkPrinter (Printer):
    	method fancy_parts ():
    		fancy_ink_stuff ()
    		clean_excess_ink ()
    		
    

    [SIGPIC][/SIGPIC]
  • JaninJanin Registered User
    edited November 2007
    Pointers and Arrays

    The dynamic (and some static) languages above do a very nice job of hiding implementation details for variables. However, if you want to get anywhere with C or C++ you must learn how pointers and arrays operate. The two are one and the same, so I will cover both at once.

    First, some definitions. A pointer is a variable that points to another variable. An array is like a list, but has a size fixed when it is created. Within the computer, memory can be treated as a massive one-dimensional array. When you create a variable (say, an integer) the computer will calculate the amount of memory required, allocate it from the available memory, and give you a pointer to that memory size. Anything you want can be stored in there, not just what type you originally asked for, but don't get crazy or people will hate you and your code. While in dynamic languages variables are "labels", in a static language variables are "boxes".

    There is another important difference between an array and a list. An array can only hold one type of object (specifically, each cell in an array is of a fixed size equal to the size required for each instance of the array's contained type). For example, say you were to construct an array of 4 32-bit integers. Each cell of the array will be 32 bits long, for a total of 128 bits. You can construct a list such as [1, "Hello", ["lol", "wow"]], but an array can only hold whatever the array was created for.

    Here's an example of using pointers to manipulate integer variables in C:
    int a; /* a is an integer with no set value */
    int b = 5; /* b is a separate variable, set to 5 */
    int *c = &a; /* c is a pointer to a */
    int *d = &a; /* d is a pointer to a */
    
    /*
    At this point, our memory looks like this:
    a: undefined
    b: 5
    c: <address of a>
    d: <address of a>
    */
    
    /* A pointer can be re-assigned to point to a different slot in memory */
    d = &b; /* d is now a pointer to b */
    
    /* A pointer can be "de-referenced" to access the variable it is pointing to. &#37;d is the code for a decimal integer. */
    printf ("b = %d, *d = %d\n", b, *d); /* Prints "b = 5, *d = 5" */
    
    /* If the de-referenced pointer is modified, the variable it points to is also modified. This is truly Spooky Action at a Distance */
    *d = 10;
    printf ("b = %d, *d = %d\n", b, *d); /* Prints "b = 10, *d = 10" */
    
    /* In this line, we set the value for the "a" variable without accessing it. It could be in an entirely separate part of the program */
    *c = 5;
    printf ("a = %d, *c = %d\n", c, *c); /* Prints "a = 5, *c = 5" */
    

    Now, to tie all this into arrays. An array is actually treated, internally, as a pointer. You can dereference it, modify it, whatever. What's more, you can treat normal pointers like arrays! An example:
    int array[3] = {7, 8, 9}; /* Array of 3 integers */
    int a = 5, b = 10;
    int *a_ptr = &a;
    
    /* Dereferencing an array returns the first value of that array */
    printf ("array[0] = %d, *array = %d\n", array[0], *array); /* Prints "array[0] = 7, *array = 7" */
    
    /* A pointer can be treated like an array */
    printf ("a_ptr[0] = %d\n", a_ptr[0]); /* Prints "a_ptr[0] = 5" */
    
    /* Because arrays are contiguous memory space, moving the pointer around will move around in the array */
    /* This is how the [] operator is implemented */
    printf ("array[1] = %d, *(array + 1) = %d\n", array[1], *(array + 1)); /* Prints "array[1] = 8, *(array + 1) = 8" */
    
    /* If your pointer is pointing to contiguous variables, you can do the same thing */
    printf ("b = %d, a_ptr[1] = %d, *(a_ptr + 1) = %d\n", b, a_ptr[1], *(a_ptr + 1)); /* Prints "b = 10, a_ptr[1] = 10, *(a_ptr + 1) = 10" */
    

    [SIGPIC][/SIGPIC]
  • JaninJanin Registered User
    edited November 2007
    This page reserved in case the thread gets big and I have to expand the OP or whatever.

    [SIGPIC][/SIGPIC]
  • jothkijothki Registered User regular
    edited November 2007
    Nifty.

    Something about algorithm design would probably be helpful as well. It's a bit of a broad subject, but you could mention pre and postrequisites and how you can develop a program by writing high-level pseudocode for the basic functionality and then breaking it down until you reach the level of real code.

  • marty_0001marty_0001 Registered User regular
    edited November 2007
    Ooooohhh yes! Thankyou thankyou thankyou. Exam in 3 weeks. Unless I procrastinate severely I will be posting a query or two here.

  • LindenLinden Registered User regular
    edited November 2007
    Janin wrote: »
    Lisp - A somewhat popular language following the "functional" paradigm, the basis for programs such as GNU Emacs and...uh...

    Which one? :P

    There's also AutoCAD, apparently.

    I'd like to see more detail on paradigm, although that may be out of focus for this sort of thread. And god this would be easier to read with some parallel to syntax highlighting – and I'd certainly expect that to be present in any commonly used editor these days*. It might also help to mention what's actually happening in the Fibonacci example – if one's introducing functions, then recursion should probably be covered.

    Very nice, though. I sort of want to expand on the Functions section in general, actually.

    Edit: Looking deeper, you have a rather unusual version of map. 'exists' might be a better term for it.

    *I've occasionally used nano. It mostly hurts.

    What if this weren't a rhetorical question?
  • AndorienAndorien Registered User
    edited November 2007
    When this subforum showed up, I said "Oh please let someone make a dedicated programming thread!"

  • MKRMKR Registered User regular
    edited November 2007
  • jackaljackal Registered User regular
    edited November 2007
    jQuery just abstracts away differences in the browsers' DOM right? If you aren't messing with a browser you don't really need it.

  • seabassseabass Doctor MassachusettsRegistered User regular
    edited November 2007
    Lisp is a fine language, but I'd hardly say its popular. I mean sure, you're not going to meet a computational linguist that doesn't use it, but thats like a whole five people.

    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.

    Run you pigeons, it's Robert Frost!
  • jackaljackal Registered User regular
    edited November 2007
    seabass wrote: »
    Lisp is a fine language, but I'd hardly say its popular. I mean sure, you're not going to meet a computational linguist that doesn't use it, but thats like a whole five people.

    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# <img class=" title=":lol:" class="bbcode_smiley" />

    I'm a CLR whore.

  • seabassseabass Doctor MassachusettsRegistered User regular
    edited November 2007
    F#, thats Microsoft's new functional language do-hickey, right? How is that? Are we talking C# where they stripped the loops and make you do iteration by recursion, or is there some real meat and potatoes to be had there? Better pattern matching, good reg-exp handling, evaluating arbitrary strings as code, anything super useful that you've seen so far?

    Run you pigeons, it's Robert Frost!
  • jackaljackal Registered User regular
    edited November 2007
    seabass wrote: »
    F#, thats Microsoft's new functional language do-hickey, right? How is that? Are we talking C# where they stripped the loops and make you do iteration by recursion, or is there some real meat and potatoes to be had there? Better pattern matching, good reg-exp handling, evaluating arbitrary strings as code, anything super useful that you've seen so far?

    It is an ML family language. It is very similar to OCaml.

  • JaninJanin Registered User
    edited November 2007
    Linden wrote: »
    And god this would be easier to read with some parallel to syntax highlighting – and I'd certainly expect that to be present in any commonly used editor these days*.

    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.
    Linden wrote: »
    It might also help to mention what's actually happening in the Fibonacci example – if one's introducing functions, then recursion should probably be covered.

    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).
    Linden wrote: »
    Very nice, though. I sort of want to expand on the Functions section in general, actually.

    If you, or anybody has improvements they'd like to see in the OP, write them and I'll edit them in.
    Linden wrote: »
    Edit: Looking deeper, you have a rather unusual version of map. 'exists' might be a better term for it.

    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.
    Linden wrote: »
    *I've occasionally used nano. It mostly hurts.

    Nano has syntax highlighting.
    jackal wrote: »
    jQuery just abstracts away differences in the browsers' DOM right? If you aren't messing with a browser you don't really need it.

    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")
    })
    

    [SIGPIC][/SIGPIC]
  • LindenLinden Registered User regular
    edited November 2007
    Janin wrote: »
    Linden wrote: »
    *I've occasionally used nano. It mostly hurts.

    Nano has syntax highlighting.

    I have no idea how I missed that. That is truly wonderful - thanks!

    What if this weren't a rhetorical question?
  • LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    I guess it's not a beginner topic, but still, once you get the basics you start having ideas for larger, more useful programs than "Hello world!" And then you wonder how people manage to throw so much stuff together without getting confused, and how exactly multiple source files interact with each other in various languages. (Why do tutorials never cover this? I had to design all my own experiments to figure out how C worked with multiple source files, and I own books on the damn language.) I would be very interested in whether anyone has any good links or information on design paradigms, especially as relates to games. For example, I've implemented a model/view/controller system in a roguelike I'm writing in Python, but honestly I'm not totally sure why since I think of a game as being highly linear (get input, do logic and animation, tell your graphics library to draw the scene). Also, I'm none too happy with my basic mediator implementation that sends all messages to all listeners, when really the display doesn't care about the player entering a command.

  • JaninJanin Registered User
    edited November 2007
    I guess it's not a beginner topic, but still, once you get the basics you start having ideas for larger, more useful programs than "Hello world!" And then you wonder how people manage to throw so much stuff together without getting confused, and how exactly multiple source files interact with each other in various languages. (Why do tutorials never covered this? I had to design all my own experiments to figure out how C worked, and I own books on the damn language.) I would be very interested in whether anyone has any good links or information on design paradigms, especially as relates to games. For example, I've implemented a model/view/controller system in a roguelike I'm writing in Python, but honestly I'm not totally sure why since I think of a game as being highly linear (get input, do logic and animation, tell your graphics library to draw the scene). Also, I'm none to happy with my basic mediator implementation that sends all messages to all listeners, when really the display doesn't care about the player entering a command.

    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?

    [SIGPIC][/SIGPIC]
  • Typhus733Typhus733 Yip! Registered User regular
    edited November 2007
    I'm in the midst of my second year in a C++ programming class and in my first with Python. Definitely preferring the latter language. I've already gotten classes mostly down after only a couple of months with python whereas with a year and several months I still find classes sketchy in C++. On to an actual question, with learning C++, pointers were just recently started on and for the life of my I don't see why they are so important. My teacher hasn't been able to shed any light on that and honestly my class has all came to this same problem. When are pointers really all that vital?

  • MKRMKR Registered User regular
    edited November 2007
    Typhus733 wrote: »
    I'm in the midst of my second year in a C++ programming class and in my first with Python. Definitely preferring the latter language. I've already gotten classes mostly down after only a couple of months with python whereas with a year and several months I still find classes sketchy in C++. On to an actual question, with learning C++, pointers were just recently started on and for the life of my I don't see why they are so important. My teacher hasn't been able to shed any light on that and honestly my class has all came to this same problem. When are pointers really all that vital?

    They're handy for passing variables by reference to functions, rather than by value. There's probably some situation where that's useful. :D

  • JaninJanin Registered User
    edited November 2007
    Typhus733 wrote: »
    On to an actual question, with learning C++, pointers were just recently started on and for the life of my I don't see why they are so important. My teacher hasn't been able to shed any light on that and honestly my class has all came to this same problem. When are pointers really all that vital?

    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.

    [SIGPIC][/SIGPIC]
  • MonoxideMonoxide Registered User, ClubPA regular
    edited November 2007
    Janin wrote: »
    Typhus733 wrote: »
    On to an actual question, with learning C++, pointers were just recently started on and for the life of my I don't see why they are so important. My teacher hasn't been able to shed any light on that and honestly my class has all came to this same problem. When are pointers really all that vital?

    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.

  • SmasherSmasher Starting to get dizzy Registered User regular
    edited November 2007
    Times pointers are useful or necessary:

    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.

  • JaninJanin Registered User
    edited November 2007
    Monoxide wrote: »
    Janin wrote: »
    Typhus733 wrote: »
    On to an actual question, with learning C++, pointers were just recently started on and for the life of my I don't see why they are so important. My teacher hasn't been able to shed any light on that and honestly my class has all came to this same problem. When are pointers really all that vital?

    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.

    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.

    [SIGPIC][/SIGPIC]
  • jothkijothki Registered User regular
    edited November 2007
    Janin wrote: »
    Monoxide wrote: »
    Janin wrote: »
    Typhus733 wrote: »
    On to an actual question, with learning C++, pointers were just recently started on and for the life of my I don't see why they are so important. My teacher hasn't been able to shed any light on that and honestly my class has all came to this same problem. When are pointers really all that vital?

    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.

    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.

  • JaninJanin Registered User
    edited November 2007
    jothki wrote: »
    Janin wrote: »
    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.

    [SIGPIC][/SIGPIC]
  • LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    Janin wrote: »
    I guess it's not a beginner topic, but still, once you get the basics you start having ideas for larger, more useful programs than "Hello world!" And then you wonder how people manage to throw so much stuff together without getting confused, and how exactly multiple source files interact with each other in various languages. (Why do tutorials never covered this? I had to design all my own experiments to figure out how C worked, and I own books on the damn language.) I would be very interested in whether anyone has any good links or information on design paradigms, especially as relates to games. For example, I've implemented a model/view/controller system in a roguelike I'm writing in Python, but honestly I'm not totally sure why since I think of a game as being highly linear (get input, do logic and animation, tell your graphics library to draw the scene). Also, I'm none to happy with my basic mediator implementation that sends all messages to all listeners, when really the display doesn't care about the player entering a command.

    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?

    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.

  • LoneIgadzraLoneIgadzra Registered User regular
    edited November 2007
    Janin wrote: »
    jothki wrote: »
    Janin wrote: »
    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.

    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.

  • JaninJanin Registered User
    edited November 2007
    Janin wrote: »
    I guess it's not a beginner topic, but still, once you get the basics you start having ideas for larger, more useful programs than "Hello world!" And then you wonder how people manage to throw so much stuff together without getting confused, and how exactly multiple source files interact with each other in various languages. (Why do tutorials never covered this? I had to design all my own experiments to figure out how C worked, and I own books on the damn language.) I would be very interested in whether anyone has any good links or information on design paradigms, especially as relates to games. For example, I've implemented a model/view/controller system in a roguelike I'm writing in Python, but honestly I'm not totally sure why since I think of a game as being highly linear (get input, do logic and animation, tell your graphics library to draw the scene). Also, I'm none to happy with my basic mediator implementation that sends all messages to all listeners, when really the display doesn't care about the player entering a command.

    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?

    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.

    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.

    [SIGPIC][/SIGPIC]
  • JaninJanin Registered User
    edited November 2007
    Janin wrote: »
    jothki wrote: »
    Janin wrote: »
    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.

    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.

    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;
    

    [SIGPIC][/SIGPIC]
  • AndorienAndorien Registered User
    edited November 2007
    Smasher wrote: »
    Times pointers are useful or necessary:

    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.

    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.

  • MiserableMirthMiserableMirth Registered User regular
    edited November 2007
    Hey, I like this thread.

    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)?

  • SnowconeSnowcone Registered User
    edited November 2007
    jackal wrote: »
    jQuery just abstracts away differences in the browsers' DOM right? If you aren't messing with a browser you don't really need it.

    In essence. If your code is all server side, you don't need it.

  • MKRMKR Registered User regular
    edited November 2007
    Hey, I like this thread.

    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)?

    Dev-C++ hasn't seen an update in years. :P

    http://forums.codeblocks.org/index.php?board=20.0

  • AndorienAndorien Registered User
    edited November 2007
    MKR wrote: »
    Hey, I like this thread.

    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)?

    Dev-C++ hasn't seen an update in years. :P

    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!

  • MiserableMirthMiserableMirth Registered User regular
    edited November 2007
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    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)?

    Dev-C++ hasn't seen an update in years. :P

    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.

  • AndorienAndorien Registered User
    edited November 2007
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    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)?

    Dev-C++ hasn't seen an update in years. :P

    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

  • MKRMKR Registered User regular
    edited November 2007
    Andorien wrote: »
    Andorien wrote: »
    MKR wrote: »
    Hey, I like this thread.

    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)?

    Dev-C++ hasn't seen an update in years. :P

    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.

  • MonoxideMonoxide Registered User, ClubPA regular
    edited November 2007
    What's wrong with vi and g++?

    People are so picky these days.

«13456763
This discussion has been closed.