Why are all of the tutorials for C++?


^ Please, use quotes. Half the time I don't know what or who you're referring to as you leap from one issue to the next. Also please use less and/or parentheseis sentences. Currently I can't make out where your non-parenthesis sentences end half the time. Your posts read like Yahtzee speaks in "No punctuation", or like you have one helluva sugar rush :) .


Asm has its advantages in certain situations, like heavy optimization and using processor specific stuff. On the other hand, it makes your programs very hard to port to another instruction set. Asm is also good to learn for the sake of basic understanding of how computer programs work. All these considered, it's still nowhere near a priority for most programmers, unless you're in a specific field that requires it. It's all a matter of perspective.


There are three points of view I'd like to add to your comments about C's superior attributes in performance. Readability, development speed and difficulty.


In my opinion, after the absolute requirements of the program, such as running full speed on target hardware, have been met the most important property of code is readability. Those OO concepts make the code easier read, because the programmer has a richer set of concepts at his disposal to describe his program. The reader doesn't have to find out that the programmer has used "my yet another object implementation with quirky properties", but can rely on stuff happening the same way. This results in less code that is more readable because there's fewer concepts the reader has to learn from it.


Development speed is in my opinion mainly important for two reasons: motivation and getting stuff done. Motivation is the key word here for new programmers. If it takes too long to get anything visible or something to try out, motivation drops because you may feel like you're doing a lot but not accomplishing much. After you've done a few applications this becomes less and less of a problem, because you know excatly where you are in terms of getting something to try out. Getting stuff done refers to those gazillions of unfinished projects, that have been left to the "I'll get on that later" limbo. If you get the first usable version of your program out in six days instead of six weeks, you are a lot more probable to get something made that people actually benefit from. A programmer's mind- well mine at least -is fickle and easily turns to a more interesting project. If you get the first, may it be efficient or not, version of your program out before you switch interests, you have actually accomplished something instead of creating "yet another great start for a project". Higher level languages let you accomplish this by letting you describe your program in fewer terms and using pre-prepared patterns found efficient in that very context.


Difficulty, in this case mostly in terms of entry barrier is in my experience the main thing turning novice programmers off. For example, compare the C/SDL and python/pygame implementations of drawing an image to the screen. Now count the number of concepts required to understand the code. Now divide those concepts into two groups: language-related and application-related and compare the size of those groups. It's easier to make things in higher level, because you can concentrate on your application instead of the stuff a lot of more skilled coders have already done a million plus one times.


I'm not refuting your points here. These are parallel points of view, not conflictiong ones. The priority order depends on who you're asking, but in my opinion concentrating mainly on one aspect like performance is not constructive.
 
(Trimmed entirely, because there's no need to repeat it, lol.)
+1.


Argh, I said i'd no longer post, and what I meant was about anything, but hey, i'm posting a positive response, so meh :D .


I completely agree. Part of the reason I said in my first post to try whatever language first (like a 'fun' one) before you try something a little more 'mind numbing' (though not to us who are fans of low level languages, it will seem this way to a newcomer ('newbie' tends to be taken offensively)).


I have >200000 unfinished projects under my belt :) . While I agree with you, for me, most of them due to lack of time, not motivation.(not because it was C in this case - honestly python/etc would not have improved the situation after i've set up my base engine) One i'd really love to finish I had to cancel because I didn't want Nintendo to sue my ass :( .

ASM can obfuscate _very-very-very_ quickly. One of the first worms was filled with jumps to obfuscate its code(The file was a .COM so i'm guessing it was indeed written in assembly, save space mostly), to great success (a disassembly of code like this can be completely unnavigable(no labels) - however I think the original assembler input file (actual source) was obtained). I base this information on the book 'Underground', which is a good read, apparently a true story. I'm going to read it again...


C can too, but it's not so bad (there's some English in there).


I guess i'm just so used to C, but I fail to see how pygame's drawing an image on the screen is harder than C's. Possibly, setting up libraries, especially on Winblows(that's the reason I didn't really get into graphical programming in C/C++ until after moving to Linux).


I can see how python is SO much easier for writing 'applications' (though i've never really written a useful program (read: anything not game/music/hobby related in any way) in any language - besides some math stuff. I'll admit i've been spoiled, i've never needed a program that wasn't already written. I've written a BBS and webserver before. Both I just scrapped because they weren't worth writing anymore - here is where python would have been awesome, but for the latter, would defeat the purpose (was intended to serve an error page while doing stuff - thus could not use much cpu)) that achieve a goal other than amusement, but not so much for games. It's more readable, certainly more so than my code.


Please note that i've not done python/perl for ages. There's probably a make_awesome_game(string genre); (psuedocode for language independance) or similar now ;) .


I tend to roll my own 'libraries' any time it's possible. The only libraries I use atm for games is SDL and SDL_image. I was using SDL_ttf, but moved to my own bitmap font renderer (Crappy on purpose font ftw! Screenshot at the bottom (for lolz). Considering change to the font used in my OS(second pic), which is smaller (bitwise 8x8) and arguably prettier. A little slower(it needs putpixel, or directly accessing the screen surface)). One day i'll get around to dropping SDL_image too (moving all my SDL Surfaces into raw files to be loaded into RAM, (maybe decompressed) and to be pointed to by pointers. But that's enough offtopic).


I'm derailing again.


I'd have used more quotes, normally. I should have. I knew it was a jigsaw. Sorry about that :(


Also thx, for making a calm reply :) .


<(obvious)derail>


"Don't worry, no fire behind this door" (name the game this is from!).

The first pic shows what is possible (yes, it is! - oh, well, I did use a map editor, itself raised from the dead! just code, by me) with just code. (And gimp for drawing the graphics - badly as you can see :D ). Ignore any bad code that may be visible here :eek: ;) . Not the best example. Note: You don't need, and I didn't need, codeblocks. I just like its interface to GDB (code stepping ftw). I wrote a huge chunk of the code in Nano in fact. You get way less distracted working on a terminal without X (you can run your SDL programs on the framebuffer device - or at least you _could_ in (x)ubuntu, it doesn't seem to work properly for me now.


Also, sorry, but, see the title of the window in the first pic.


Originally Foo was a placeholder, but I think it's staying. BTW - I might enter this game in the Free for all compo in march - if you're allowed to enter prior-written code. It's always been for the Pandora. It was the native 800*480 but I couldn't stand the >20% CPU usage (on my computer, i'm pandoraless. On my computer, I don't get a hardware surface - so I imagine on pandora it's way better - like at school, on Winblows, I see <5% CPU usage :D . But the computers at school are more powerful), so I dropped the res and it was below <20%. It's 400*240*16bits. Could do with further optims, since I've no idea of the format of the graphics that are loaded in. And my player graphic uses transparency! Big no-no!


The second pic is my OS for x86's experimental gfx mode. Just C code(no libraries either). windows (as in the boxes where programs show their output, not the OS) can be added/removed (so can icons, there's functions for it, but they aren't called by the user - Fun Fact, I made icons before windows). I should not have been doing gfx at all yet, since I don't have multitasking or real memory management (dummy free and malloc returning a pointer subtracted from the last 'alloced' memory...).

</derail>

blaRPGfontrenderer.png

OSGFX.png
 
Those OO concepts make the code easier read, because the programmer has a richer set of concepts at his disposal to describe his program.
That depends a lot on who's looking at the code and to what degree OOP is being used. For someone who does not have lots of experience with using advanced OOP concepts it is actually harder to read. And if you have code that's filled with an absolutely overkilling amount of classes (that's e.g. nothing unusual for Java code) it can really be a pain in the ass to read, even for someone who's very familiar with OOP concepts.


The same counts for imperative code, if it has at least a basic structure it is usually rather easy to read, ppl coming from OOP may have a few difficulties because they are not used to it. However, especially beginners may tend to drop into spaghetti code, which is again very hard to read for anyone, in the end even for the coder himself.
 
^ If I may, this is a nice place for an analogy. Consider learning a foreign language. Reading OO code with imperative background is sort of like trying to understand complex sentences with only the basic vocabulary. Simpler sentences containing only basic words are of course easier, but if you have a larger vocabulary, you can have richer language and more expression power. It is, for example, easier to explain programming stuff to a layman by skipping all the jargon and limiting oneself to using easy words, but it's much more efficient and quicker if the listener already knows the jargon. You can say the same things with a smaller vocabulary, but it takes more space. On the other hand it requires less pre-existing knowledge.


I write my code assuming the reader knows modern OO practices, architecture models, design patterns and all that basic CS stuff they teach today. In my experience larger common knowledge base leads to more expression power and better readability.


EDIT: Also, OO, like any other paradigm, can of course be abused. It's easy to see everything as nails when you have a nice hammer. :)
 
Last edited by a moderator:
Not necessarily. Especially in C there are concepts being used that OOP coders don't know because they would do it entirely different using OOP concepts. For a simple example, look at SDL's event handling, it uses a simple trick to use some kind of inheritance for having a single event structure that can be any kind of event. Or for a more complex example, GObject uses many of those concepts.

EDIT: Also, OO, like any other paradigm, can of course be abused. It's easy to see everything as nails when you have a nice hammer. :)
Just that in Java it might be consider to be "efficient" to smash everything :p
 
Last edited by a moderator:
Not necessarily. Especially in C there are concepts being used that OOP coders don't know because they would do it entirely different using OOP concepts. For a simple example, look at SDL's event handling, it uses a simple trick to use some kind of inheritance for having a single event structure that can be any kind of event. Or for a more complex example, GObject uses many of those concepts.
Yeah, unions are sometimes nice, but I consider them kinda kludgy. You have to have the same identifier field in each "subtype" (I hate boilerplate) and IIRC can't check type correctness at compile time. Correct me if I'm wrong, but aren't unions just a kind of syntactic sugar for void pointers? Basically they point to a place in memory and leave it to you to figure out what's there. Yes, they handle reserving enough memory so you won't overwrite anything else (which increases memory consumption btw, though it's not really relevant here), but you can still read/write them as something they are not. Classes handle compile time type checking, require common variables between subtypes to be declared only once (at parent class) and reserve only the amount of memory the subtype actually needs.


GObject has some nice properties, but it has too much boilerplate overhead and seems overall too "hackish" to my taste. It just doesn't feel elegant.


I must admit I'm stretching my C knowledge here. Please correct me if I remember incorrectly.

Just that in Java it might be consider to be "efficient" to smash everything :p
Well it either is or isn't efficient :) . Java is a curious language because of its object-centric approach (nothing like smalltalk though). You basically can't do anything without classes, which makes you use some quirky patterns.


BTW, I'm not mainly a Java programmer myself. More of a C++ / script language guy :) . Java is too "enterprisey" for most of what I like to do :) . Though I like the concept of actual interfaces in Java compared to C++.
 
XxionxX: You should learn ASM, yes, but you should not necessarily use it as your primary language. My biased opinion is that you should use C, of course, and I can say there's definitely nothing wrong with it for game programming. But there's no harm done in using a C++ compiler to compile your games instead of C compiler. Way back when I first started with SDL, my program refused to compile with a C compiler, I was no doubt doing something stupid, but the compiler was saying there was issues in the library file (SDL/SDL.h), so being a noob, I said wtf, and used g++ where my C worked perfectly. Plus doing this would let you tell your boss that you're using C++, to please him, if you ever do programming for work. He often won't know any better. New/delete are actually very nice additions, but things like streams (that look like bitshifts, gets me every time) are not all that useful to a game programmer.


Jump in and try C. If you don't like it, try ASM, then you will(nah, ASM ftw) try alternatives until you find something that you like. I missed the ultimate goal - make an awesome game(but the biggest thing to remember is that your first game will no doubt be crap, it's normal. Nobody liked Super Hit-Enter-And-Get-an-Error-in-C64-Basic Brothers either(no, I didn't actually name it that). Don't try tetris first, I really don't get why people recommend it. Go for moving characters around with the keyboard. Then build up on that.)
Yah, I know that ASM is not really friendly to new programmers, especially when it comes to finding tutorials! I am starting with C and I am hoping to make a platformer because it seems easy enough from what I understand. I plan on learning ASM, but for now I am concentrating on getting started with C. I have had a lot of trouble getting to the point where I can actually make something. It feels like every tutorial is teaching me the same thing about pointers, if statements, and basic syntax. I just want to get started! I make webpages in HTML and CSS (with a smattering of php for ease of maintainability) and I know that I learn best by doing. When I started with webpages I made some shitty ones, but when I got the hang of it I went back and made them better. Now I make a pretty decent webpage if I do say so myself. I finally decided to follow a game tutorial in the other thread because I am the kind of person who needs to see results, because if I don't see results I tend to give up. I like the idea of game programming, but I really want to be able to make all kinds of applications. I feel like game programming will get some of the basics rooted in my head so I can move on to bigger projects. I picked C because it seems like everyone uses it to do just about everything, and I want to be able to work on as many platforms and devices as possible (though that is far in the future).


I am glad to have sparked such a passionate debate! I am learning a lot! What is the difference between ASM and bytecode? They seem really similar.
 
I am glad to have sparked such a passionate debate! I am learning a lot! What is the difference between ASM and bytecode? They seem really similar.

Assembly is basically machine code with aliases. Instead of typing the raw numerical values that correspond to instructions and parameters you use easier-to-read aliases, like "ADD r1 r2" or "JMP foo".


Bytecode is kind of like machine code for a virtual machine. It's designed to be quickly interpreted by the VM to native machine code (not a direct translation, result depends on program state and VM). Because bytecode depends only on the VM's features, it's platform independent. For example a Java compiler creates .class files which contain the bytecode and are imported by the VM when a program requiring them is executed. The same with pythons .pyc-files. Runnable bytecode files can be distributed like binaries and ran on any platform the required VM has been ported to.


I simplified a bit, but that's basically the gist of it.
 
Last edited by a moderator:
Yeah, unions are sometimes nice, but I consider them kinda kludgy. You have to have the same identifier field in each "subtype" (I hate boilerplate) and IIRC can't check type correctness at compile time. Correct me if I'm wrong, but aren't unions just a kind of syntactic sugar for void pointers? Basically they point to a place in memory and leave it to you to figure out what's there. Yes, they handle reserving enough memory so you won't overwrite anything else (which increases memory consumption btw, though it's not really relevant here), but you can still read/write them as something they are not. Classes handle compile time type checking, require common variables between subtypes to be declared only once (at parent class) and reserve only the amount of memory the subtype actually needs.

That's not how people use unions... usually they'll have a struct that contains an enum and the union. The enum identifies the union type. The enum isn't part of the union.


C++ classes and unions aren't by any means interchangeable. You can't perform polymorphism over classes, you perform polymorphism over class pointers. You also can't determine the type of a C++ class pointer at runtime without a type field; okay, you can use RTTI, but you pay for it across the board. They're really no less "syntactic sugar for void pointers" than unions are, but that kind of reasoning applies to most elements of both languages. When using unions, a type that'll have enough storage for every sub-type is exactly what you want in order to avoid more complex dynamic allocation.. if you want the latter you're just as well off doing the class-like approach of casting structs down to something common that contains the type field.


Trying to do this kind of a simple OOP in C is naturally going to have boilerplate; that's largely why languages like C++ were created. When trying to do complex inheritance trees it gets really bothersome using the encapsulated struct trick to accomplish it (I've done it a few times anyway, and yes it would have been a lot nicer in C++ - I kept things in C for other reasons), but when you have a pretty flat object hierarchy there isn't really that much difference. There's some precedence to this, you'll note "Design Patterns" recommends construction over inheritance where possible, something C is capable of at about the same level. Of course, C also lacks nice features that have less to do with OOP, like function/operator overloading and templates.


I've seen a lot of people insist on using C++ in say, emulators, where the design consists of basically just using a few singleton classes that correspond to some very high level code organization like "CPU class" and "PPU class." Here my mind is boggled by their argument that C++ is much better suited to this when you can do the same thing in C with only a slightly different syntax. You don't get implicit reference to class local storage, but a lot of people don't like that for large singletons anyway since they read like global variables and have the same problem of having to track down where they belong to (not to mention dragging in the whole mess of namespaces to avoid collisions)

B-ZaR said:
Assembly is basically machine code with aliases. Instead of typing the raw numerical values that correspond to instructions and parameters you use easier-to-read aliases, like "ADD r1 r2" or "JMP foo".

It's worth pointing out that the aliases go well beyond machine code; you mentioned labels (the assembler resolving code and data locations symbolically) but there's also constants, immediate math, comments, and most assemblers have macros.. Reason why these things are worth mentioning is to paint a picture of how differently code written in assembly looks from code that has been disassembled, even though both are in the same language.
 
XxionxX: You should learn ASM, yes, but you should not necessarily use it as your primary language. My biased opinion is that you should use C, of course, and I can say there's definitely nothing wrong with it for game programming. But there's no harm done in using a C++ compiler to compile your games instead of C compiler. Way back when I first started with SDL, my program refused to compile with a C compiler, I was no doubt doing something stupid, but the compiler was saying there was issues in the library file (SDL/SDL.h), so being a noob, I said wtf, and used g++ where my C worked perfectly. Plus doing this would let you tell your boss that you're using C++, to please him, if you ever do programming for work. He often won't know any better. New/delete are actually very nice additions, but things like streams (that look like bitshifts, gets me every time) are not all that useful to a game programmer.


Jump in and try C. If you don't like it, try ASM, then you will(nah, ASM ftw) try alternatives until you find something that you like. I missed the ultimate goal - make an awesome game(but the biggest thing to remember is that your first game will no doubt be crap, it's normal. Nobody liked Super Hit-Enter-And-Get-an-Error-in-C64-Basic Brothers either(no, I didn't actually name it that). Don't try tetris first, I really don't get why people recommend it. Go for moving characters around with the keyboard. Then build up on that.)
Yah, I know that ASM is not really friendly to new programmers, especially when it comes to finding tutorials! I am starting with C and I am hoping to make a platformer because it seems easy enough from what I understand. I plan on learning ASM, but for now I am concentrating on getting started with C. I have had a lot of trouble getting to the point where I can actually make something. It feels like every tutorial is teaching me the same thing about pointers, if statements, and basic syntax. I just want to get started! I make webpages in HTML and CSS (with a smattering of php for ease of maintainability) and I know that I learn best by doing. When I started with webpages I made some shitty ones, but when I got the hang of it I went back and made them better. Now I make a pretty decent webpage if I do say so myself. I finally decided to follow a game tutorial in the other thread because I am the kind of person who needs to see results, because if I don't see results I tend to give up. I like the idea of game programming, but I really want to be able to make all kinds of applications. I feel like game programming will get some of the basics rooted in my head so I can move on to bigger projects. I picked C because it seems like everyone uses it to do just about everything, and I want to be able to work on as many platforms and devices as possible (though that is far in the future).


I am glad to have sparked such a passionate debate! I am learning a lot! What is the difference between ASM and bytecode? They seem really similar.

The difference between ASM and bytecode is that ASM is for elves, GNOMEs and GNUshumans to read. Bytecode is for a program to read.


Statements like:



Code:
  INC $DO20

  DEC $D021

  JMP $C000
are ASM, where bytecode looks more like: (btw, the code below does not equal the code above...)



Code:
  10110011 (binary) (or B3 hex or 179 decimal or 263 oct)

  01001100 (or 4C hexadecimal or 76 decimal or 114 octal)

  10111010 (or ...meh stuff it)

Bytecode generally means instructions to be executed by a VM (A program on your computer), and not a real machine, which is generally called 'machine code', or known as a 'binary'(it's all binary in a computer, but it's what it's called).



ASM also, as has been mentioned, has a thing called a 'lable'.





Code:
loop:

  INC $D020

  DEC $D021

  JMP loop



See here, I don't need to put in the address like I did before? Lables make it _so_ much easier to both read and write ASM, as opposed to machine code/bytecode. This also works for making variables





Code:
[ORG 0xD020]

variable: ;this is a lable at $D020. Normally there'd be a .db or something after this to make sure code doesn't get put there, but all our code is before this address.

[ORG 0xC000]

loop:

 INC variable ; increment our variable

 JMP loop ; loop
.



I'd give a tut on ASM pointers, but that's different between archs, and is a bit too complicated for a forum post (and my knowledge is a lil' shaky...)



But I fail at explaining, so please do find another source when you do learn ASM ;) .



Also, and btw i'm pretty sure you do know this, don't open up a program in a text editor expecting to see a whole lot of ones and zeros. You won't. You'll see the code's ASCII character for each byte. (I used to think naming your program 'virus' actually made it a a virus...)



Um, but yeah, it's explained better below(or above, depending where you read :) )...



One thing I can recommend, is to NOT jump right into graphics. (I hope you don't want to make a platformer to enter the competition. That's a recipe for disaster, entering your first project in a compo). Start with a "Console" program. Print to screen, practise with your pointers, maybe make a linked list(try and save that linked list to file. Hell, I know. It's easiest to make an array of elements from the linked list.). Make a text based adventure, don't worry about things like regular expressions (regex) and other AI, just accept simple statements like "north", "east" etc, by checking with 'strcmp'.



Code:
//For the reader: Get input from the user, put it in a char buffer called inputbuf

if(!strcmp("north",inputbuf))//do what you do when you go north.



If you're stuck, i'll give you the source to my Text-RPG(which isn't exactly neat, mind...and I never finished it but it does do stuff). It's written in C. I think I gave you too much info already, please don't get confused, instead ignore me!



On a console you don't need to do as much dynamic allocation either, which I suppose could be a little difficult (strangely, and I don't mean to brag, it never affected me...). When doing graphics, you're gonna want to know your arrays, pointers, linked lists and memory allocation super well. Don't think that means you need to become a superstar programmer, it will really come very quickly, I promise. You'll be drawing Mario's quest to save Peach for the 1000th time to the screen in no time :) .



The other thing is on a console, you don't use graphics so you don't suffer from artist block (well, your storylines might, but it's not necessary to see stuff, just write stupid stuff :) )



Are you on GNU/Linux, or a BSD(ugh netbsd libs :( )? If not, I can strongly recommend you at least run (x or l)ubuntu in a VM to do your dev. Windows is a pain to dev in, especially if you wanna port to the pandora. "sudo apt-get install build-essentials" should set you up (from a terminal). you'll have to call gcc from a terminal too, when you want to compile(or you can make a makefile). If that's not convienient, or if you want it a little more pretty, "sudo apt-get install codeblocks" (you'll need to name your source files .c to compile them with gcc and not g++. There's also some flag voodoo alternatives, not good unless you want to read _more_ docs :) )



I am glad to have sparked such a passionate debate! I am learning a lot! What is the difference between ASM and bytecode? They seem really similar.


Assembly is basically machine code with aliases. Instead of typing the raw numerical values that correspond to instructions and parameters you use easier-to-read aliases, like "ADD r1 r2" or "JMP foo".



Bytecode is kind of like machine code for a virtual machine. It's designed to be quickly interpreted by the VM to native machine code (not a direct translation, result depends on program state and VM). Because bytecode depends only on the VM's features, it's platform independent. For example a Java compiler creates .class files which contain the bytecode and are imported by the VM when a program requiring them is executed. The same with pythons .pyc-files. Runnable bytecode files can be distributed like binaries and ran on any platform the required VM has been ported to.



I simplified a bit, but that's basically the gist of it.




Yeah, unions are sometimes nice, but I consider them kinda kludgy. You have to have the same identifier field in each "subtype" (I hate boilerplate) and IIRC can't check type correctness at compile time. Correct me if I'm wrong, but aren't unions just a kind of syntactic sugar for void pointers? Basically they point to a place in memory and leave it to you to figure out what's there. Yes, they handle reserving enough memory so you won't overwrite anything else (which increases memory consumption btw, though it's not really relevant here), but you can still read/write them as something they are not. Classes handle compile time type checking, require common variables between subtypes to be declared only once (at parent class) and reserve only the amount of memory the subtype actually needs.


That's not how people use unions... usually they'll have a struct that contains an enum and the union. The enum identifies the union type. The enum isn't part of the union.



C++ classes and unions aren't by any means interchangeable. You can't perform polymorphism over classes, you perform polymorphism over class pointers. You also can't determine the type of a C++ class pointer at runtime without a type field; okay, you can use RTTI, but you pay for it across the board. They're really no less "syntactic sugar for void pointers" than unions are, but that kind of reasoning applies to most elements of both languages. When using unions, a type that'll have enough storage for every sub-type is exactly what you want in order to avoid more complex dynamic allocation.. if you want the latter you're just as well off doing the class-like approach of casting structs down to something common that contains the type field.



Trying to do this kind of a simple OOP in C is naturally going to have boilerplate; that's largely why languages like C++ were created. When trying to do complex inheritance trees it gets really bothersome using the encapsulated struct trick to accomplish it (I've done it a few times anyway, and yes it would have been a lot nicer in C++ - I kept things in C for other reasons), but when you have a pretty flat object hierarchy there isn't really that much difference. There's some precedence to this, you'll note "Design Patterns" recommends construction over inheritance where possible, something C is capable of at about the same level. Of course, C also lacks nice features that have less to do with OOP, like function/operator overloading and templates.



I've seen a lot of people insist on using C++ in say, emulators, where the design consists of basically just using a few singleton classes that correspond to some very high level code organization like "CPU class" and "PPU class." Here my mind is boggled by their argument that C++ is much better suited to this when you can do the same thing in C with only a slightly different syntax. You don't get implicit reference to class local storage, but a lot of people don't like that for large singletons anyway since they read like global variables and have the same problem of having to track down where they belong to (not to mention dragging in the whole mess of namespaces to avoid collisions)



B-ZaR said:
Assembly is basically machine code with aliases. Instead of typing the raw numerical values that correspond to instructions and parameters you use easier-to-read aliases, like "ADD r1 r2" or "JMP foo".


It's worth pointing out that the aliases go well beyond machine code; you mentioned labels (the assembler resolving code and data locations symbolically) but there's also constants, immediate math, comments, and most assemblers have macros.. Reason why these things are worth mentioning is to paint a picture of how differently code written in assembly looks from code that has been disassembled, even though both are in the same language.


C can get really messy when you have to hack around some limitations, but to a code hacker this code hacking can be really fun! I agree, to those used to C, OOPs can be hard to understand (yeah I got no idea how all that OOP stuff works :) ).



One thing i'm commonly seen doing in linked lists in C is typehacking my structs





Code:
typedef struct{

  unsigned char val;

  void * next;

  void * prev;

}thack;

typedef struct{

  unsigned char val;

  thack * next;

  thack * prev;

}val_list;

to get around the void pointer 'not being a structure or union'. Casting wasn't working for me when I first did this so it sorta stuck. There's probably a way around this and i'm doing something wrong, but hey it does work.



The way i'm often using unions is this:





Code:
typedef struct{

   unsigned char b1:1;

   unsigned char b2:1;

   unsigned char b3:1;

   unsigned char b4:1;

   unsigned char b5:1;

   unsigned char b6:1;

   unsigned char b7:1;

   unsigned char b8:1;

}byteflag;


typedef union{

   byteflag bits;

   unsigned char rawval;

}charflag;


There's a copy of that code in almost every program I write :) .


Don't try and understand that code if you don't see what's going on - you don't need to know this until much later, don't get discouraged, and I can tell you're quite intelligent, you should catch on straight away, so just get in there! :D .


Btw - it's not completely necessary, but I hope your math is good. When you get into graphics, you'll find sin/cos/tan are used pretty heavily (scaling, rotation, demos where you do plasma effects, and even that humble sinescroller effect(use a sinetable!)). Just because your math isn't too great doesn't mean you can't code, so again relax.


I'll help you if you do get stuck, just PM me. Don't overdo it tho, it's not a 'three wishes' kind of thing, but I am a real elf/GNOME/GNUhuman.


EDIT: I meant 'label' :p
 
Last edited by a moderator:
[meta]I apologize in advance for any mistakes in this post because I just woke up. Also the previous post was written a bit drunk, but seems to have turned out ok.[/meta]

That's not how people use unions... usually they'll have a struct that contains an enum and the union. The enum identifies the union type. The enum isn't part of the union.


C++ classes and unions aren't by any means interchangeable. You can't perform polymorphism over classes, you perform polymorphism over class pointers. You also can't determine the type of a C++ class pointer at runtime without a type field; okay, you can use RTTI, but you pay for it across the board. They're really no less "syntactic sugar for void pointers" than unions are, but that kind of reasoning applies to most elements of both languages. When using unions, a type that'll have enough storage for every sub-type is exactly what you want in order to avoid more complex dynamic allocation.. if you want the latter you're just as well off doing the class-like approach of casting structs down to something common that contains the type field.


Trying to do this kind of a simple OOP in C is naturally going to have boilerplate; that's largely why languages like C++ were created. When trying to do complex inheritance trees it gets really bothersome using the encapsulated struct trick to accomplish it (I've done it a few times anyway, and yes it would have been a lot nicer in C++ - I kept things in C for other reasons), but when you have a pretty flat object hierarchy there isn't really that much difference. There's some precedence to this, you'll note "Design Patterns" recommends construction over inheritance where possible, something C is capable of at about the same level. Of course, C also lacks nice features that have less to do with OOP, like function/operator overloading and templates.
Thanks for clearing this union stuff up. As I said, this is stretching my C knowledge, which itself is based on my C++ knowledge.


I assume you mean objects and not classes in the polymorphism bit, and you're very right. If you need to know the class of an object at runtime, you'll need a separate type field. On the other hand, situations where you need to find out the type of an object in some cases stem from misusing the OO paradigm. In an optimal OO situation you'd never need the type field, but all the difference in execution path regarding the type of the object would come from different implementations of virtual methods. In some cases though, like determining what happens when this GameObject and this GameObject collide, it's a lot more practical to just add a type field.

I've seen a lot of people insist on using C++ in say, emulators, where the design consists of basically just using a few singleton classes that correspond to some very high level code organization like "CPU class" and "PPU class." Here my mind is boggled by their argument that C++ is much better suited to this when you can do the same thing in C with only a slightly different syntax. You don't get implicit reference to class local storage, but a lot of people don't like that for large singletons anyway since they read like global variables and have the same problem of having to track down where they belong to (not to mention dragging in the whole mess of namespaces to avoid collisions)
Yes, this in my opinion classifies as misuse of the OO paradigm. I've told countless students not to do a "CommandParser" class in their exercise works, because it's not a sensible class, it's a function module. As you point out, in many cases when I've talked with them about it the basic reason for making it a class is shorter function parameter lists because of member variables, which translates into a "hidden" kind of global variables. I could go on about this, but I digress. Suffice to say that what those people insist is bad OO design in my opinion. Except in Java :D .

It's worth pointing out that the aliases go well beyond machine code; you mentioned labels (the assembler resolving code and data locations symbolically) but there's also constants, immediate math, comments, and most assemblers have macros.. Reason why these things are worth mentioning is to paint a picture of how differently code written in assembly looks from code that has been disassembled, even though both are in the same language.
Yes, I wanted more to give an easy to understand contrast between the two instead of explaining both in detail. As I said it was a simplified version.


EDIT: Also thanks to WizardStandoublebeta for his lengthy explanation and further information on C's intrinsics. :)


EDIT2: I just woke up
 
Last edited by a moderator:
One thing i'm commonly seen doing in linked lists in C is typehacking my structs



Code:
typedef struct{

  unsigned char val;

  void * next;

  void * prev;

}thack;

typedef struct{

  unsigned char val;

  thack * next;

  thack * prev;

}val_list;

to get around the void pointer 'not being a structure or union'. Casting wasn't working for me when I first did this so it sorta stuck. There's probably a way around this and i'm doing something wrong, but hey it does work.




Code:
struct listitem;


struct listitem

{

    unsigned char val;

    struct listitem* prev;

    struct listitem* next;

};


so what's wrong with doing it the clean way? :p
 
One thing i'm commonly seen doing in linked lists in C is typehacking my structs



Code:
typedef struct{

  unsigned char val;

  void * next;

  void * prev;

}thack;

typedef struct{

  unsigned char val;

  thack * next;

  thack * prev;

}val_list;

to get around the void pointer 'not being a structure or union'. Casting wasn't working for me when I first did this so it sorta stuck. There's probably a way around this and i'm doing something wrong, but hey it does work.




Code:
struct listitem;


struct listitem

{

    unsigned char val;

    struct listitem* prev;

    struct listitem* next;

};



so what's wrong with doing it the clean way? : P
Erm, because I was using typedefs, and never thought to stick 'struct' before declaring my pointer ;) (not true, I tried 'struct *', as you can bet, that generated errors. Probably something about empty types, or at most 'no member 'val', etc)



I kind of dislike having to put 'struct' in front of every typedef'd struct pointer I make, it kinda kills the illusion of a type. (again, i'm probably doing something wrong - I hate coding for a forum audience, you always feel so vulnerable ;) )



As I said, I had thought there was a better way of doing it ;) .



<semi-joke>And where's the fun in the 'clean' way?</semi-joke> (Where's the fun in debugging your dodgy hacks and receiving papers on security flaws in your program all day every day.. Not that I speak from experience, I've never released any software - if I did I'm sure there'd be a lot of red faced rooted admins ;) )



for a typedef'd struct, the exact demo program I just tried, which I can't guarantee actually works as a type now (should) ;) :



Code:
struct recursive;


typedef struct{

 struct recursive * next;

}recursive;


struct{

  recursive dumb; //encase your globals in a globals struct, you won't regret it

}globals;


void doList(recursive * member){

  if(member->next)doList((recursive *)member->next);

}


int main(){

 globals.dumb.next=(struct recursive *)&globals.dumb;

 doList((recursive *)&globals.dumb); //Read the spoiler tag...

 return 31337; //Because you'd have to be to get here - PM me the solution (it's possible-or at least, it was 2 years ago) and I'll add "X is elite!" to my sig, forever. Tip: signals, ASM, lots of pop, zero pushing. Rules: No kernel hax! No hex editing!

}

//I can guarantee something's wrong here. Way too many casts. But i'm sick of this example ; ).

//Note - compiling with g++ won't work. Cba trying my typehack method instead : )


Did I forget to tell you, never ever run any code I place in a post on a forum. You never know when I had a day full of people begging to get rm'd :) . All this does is run your RAM(or your program's allocated stack) out by making infinite calls to a function. I don't mean I like to vent anger on innocent people, it's just that I'm likely to send dodgy code inadvertently(subconsciously) - like now before I remembered I like Pandora Forum users, heh. Something you should know about C programmers - most of us are insane, some of us megalomaniacs(which is not the same as elitist, mind you).


I'd never post a hidden rm -rf (well, maybe somewhere that deserved such, lol - like those 'hacking' forums, to teach them a lesson about the dangers of copy+pasting code without reading it. Wasn't this done? obviously, don't run the code at that link. Btw - I'm not affiliated with the author of this code, nor am I the author) or anything like that. This was supposed to be more of a little harmless joke.


Two thinks you can learn from that link


a ) To memorise the sequence in 'jmpcode' and avoid it.


b ) Don't be a script kiddie. (bah, lowercase b! And no emoticon!)


I recommend both.


Btw, gcc message fail


/tmp/test.c:11: note: expected ‘struct recursive *’ but argument is of type ‘struct recursive *’


(I know what it's trying to say)


EDIT: Also thanks to WizardStandoublebeta for his lengthy explanation and further information on C's intrinsics. :)

Aw, thank -you- for listening! No prob, Bob, any time. I'm not an 'expert', so you know, I've self-taught myself above a safe limit, as gfrancisdev has shown ;) .


No sarcasm, right?


(Btw I feel flattered you thought I was WizardStan :) )


p.s. bug found in board software - counts smileys in [c o d e] tags despite not drawing graphic emoticons for these. Could be working as designed ;)
 
2: in reality asm is just a few aliases for the machines opcodes, C/C++ are built ontop of asm, so anything you can do in any language, can be done in asm


so yes, you could technically do shiny OO concepts in asm, but it's so unrealistic no one is crazy enough to do it
Yeah, of course you can do it, but to do it, you'd have to make an interpreter/compiler in ASM for your own language which in turn uses OO concepts, you couldn't do it directly, because it's a feature of a programming language and not of the code. That is what I meant.

In all actuality, MOST programmers don't need to use assembly. There are just some fields where it's absolutely important and therefore shouldn't be called pointless. Either way, it's good to know for indirect reasons, hence why most universities still teach it.
Asm has its advantages in certain situations, like heavy optimization and using processor specific stuff. On the other hand, it makes your programs very hard to port to another instruction set. Asm is also good to learn for the sake of basic understanding of how computer programs work. All these considered, it's still nowhere near a priority for most programmers, unless you're in a specific field that requires it. It's all a matter of perspective.
That is what I meant. For most programmers and for most cases, ASM is useless as in "has no use". I thought the addition of "as ancient greek" would make that clear. Someone lerning programming will probably not just make stuff for embedded systems, not for years if ever, so for him, ASM would be useless.


I beg all those who love ASM pardon, I diddn't want to say that it is, for all purposes, useless.

doublebeta said:
Furthermore, (IIRC - and it might have changed)Apple's app store only allows programs written in Objective-C - so there's a platform with millions of users. So tell me now that java works everywhere useful
Well, I wouldn't call apple useful :D


(Yes. That was a Joke. You know, as in.. Ha ha and stuff :p )


>I hope you weren't hinting that history -c makes you superior


Nah, not at all. That was just meant as a joke. I do not think I'm superior to you, I just hate that whole java bashing.


I don't say anything about the rest of your post, not because it wouldn't be worth it (in fact you made some good points), but to prevent further derailing.

Make a text based adventure, don't worry about things like regular expressions (regex) and other AI, just accept simple statements like "north", "east" etc, by checking with 'strcmp'.



Code:
//For the reader: Get input from the user, put it in a char buffer called inputbuf

if(!strcmp("north",inputbuf))//do what you do when you go north.


Are you sure a text adventure is good to be recommended to a beginner? Granted, I never made one and you did, but in my mind, this is bound to get really ugly really fast if you don't exactly know what you're doing, which a new programmer probably wont (no offense). Not to speak of the whole text interpreting issue since there's nothing worse than a text adventure with a really small subset of words it understands. You can't get ye flask, but you can "take" it ;)



Also, I'd probably take inform (of zork fame) for text adventures, because it has all the language rules allready figured out. (I once learned (as in, read the language doc really concentrated :p ) Inform 6 because I wanted to make a text adventure, too bad I never had a good idea for one). But readers be warned: while it is the "default" language for text adventures, some stuff of it is really ugly and it has a syntax not really compatible with c, c++, java etc. Inform 7, which is still not that widely used (it's only about 4-5 years old), is for a programmer even worse because it looks nothing like what your common progger is used to and takes way longer to write. But on the other hand, it's easier to read even for non-programmers.

For example, you'd do a room like this:



Code:
// Inform 6:

Object Living_Room "Living Room"

     with

         description "A comfortably furnished living room.",

         n_to Kitchen,

         s_to Front_Door,

     has light;


// Inform 7:

The Living Room is a room. "A comfortably furnished living room."

The Kitchen is north of the Living Room.

The Front Door is south of the Living Room.

and it would allready handle stuff like "go north", "north", "n", "go to kitchen", "look around", "look", "examine", "exits" etc.


But I digress. Again.


EDIT: Did the.. did the board software really just color inform code in a meaningfull way? Amazing :D (Probably a coincidence and it just colors words beginning in uppercase, but still, color me surprised)
 
Last edited by a moderator:
Ok, just from the start, i'm in a hurry, can't stand leaving the post unanswered tho (yeah I know, obsessive-compulsive)

Well, I wouldn't call apple useful :D
+1


Neither; but it's what makes money (which I'm NOT interested in doing with my code ever, mind you :) )


Holy crap, I don't know why the hell I recommended a text adventure, was I on Craig's medicine?


It might've been to do with all the pointer crap I happened to do in my code (erm - yeah. Forget it :) )


My T-RPG takes super simple commands, and when I abandoned it, It had basic battling, which I was pretty proud of. But it could not take items. I started doing that, added text in the storyline to imply that it was possible, but then I sorta forgot and went to go hack at another feature. I could add it, when I get the time...mind I wrote it in like a day. I shouldn't have brought it up, that smelly mud should have remained at the bottom of the lake (to become a gem in future?).


I'd show you, what I mean, if you promise not to read the source, and just build the program - wait, scratch that, it's a bad security practise. On the weekend I'll clean my code up and release in the Off Topic section. No promises tho. I completely agree, it gets _real_ ugly. My code, made me kinda die inside ;) . Ever had that happen when you read old code?


>Nah, not at all. That was just meant as a joke. I do not think I'm superior to you, I just hate that whole java bashing.


Oh, ok, cool. Definitely no grudges held here. We all cool, provided I stop java bashing (hrrm, at least to a minimum (no more huge posts))?


>I beg all those who love ASM pardon, I diddn't want to say that it is, for all purposes, useless.


Erm, Pardoning. Um, except the interpreter/compiler bit. I'll try and make proper sense of that tomorrow. I think what you mean is that OOP is an abstraction, and that ASM programmers don't bother with abstraction. Yeah, that's part of the reason ASM is faster ;) (all those OOP-centric language fans just pulled the trigger, in hatred or realisation ;) (sorry, that's NOT a direct stab at java - and OOP is certainly worth the, also sometimes, added overhead(stuff you never actually needed but added to make it more friendly).


> Did the.. did the board software really just color inform code in a meaningfull way? Amazing :D


It does seem to detect keywords pretty well - don't want to know how it works, I'd explode or cry(aaalllll that long code for an underappreciated feature?)


Useless commenting: That inform 6 looks easiest to me, having done programming for so long - and is reminiscent of how my code _should_ have actually looked, in C (if I actually ever did the neat plans I plan out). Inform 7 looks like something I could teach my parents pretty easily.
 
It might've been to do with all the pointer crap I happened to do in my code (erm - yeah. Forget it :) )
Note to self: do not mock doublebeta because he has to put up with pointers :D

On the weekend I'll clean my code up and release in the Off Topic section.
No need to do this for me. No offense (really), but I played too many interactive fiction games with a too slow (Edit: I think I had some of that medicine too.. slow? tiny of course) grammar subset. There's nothing worse than to have to try 20 different wordings just to turn on a light or something :)

My code, made me kinda die inside ;) . Ever had that happen when you read old code?
I thinks that happens to every developer. No matter how much you allready know, there's always something you know now that you diddn't a year back or something you'd do differently today. I'm regularly temted to just delete all my old progs off of my homepage just in shame of the old code. (And sometimes because they're useless.. For example I once made a small prog in C++ that did nothing more than add two numbers of any size together (using arrays, so the max number would be (10^(INT_MAX+1))-1 ). Originally it was planned to make a complete math class for really large numbers, but I kinda lost interest and needed some stuff to put on my homepage when I made it :D ). (and yes, I use way too many brackets (I really do (and I should stop)))

don't want to know how it works, I'd explode or cry(aaalllll that long code for an underappreciated feature?)
I guess it isn'tlong code at all but some Regex hacks that just work out most of the time.. Make all uppercase words red, all words in quotes green, color some keywords like "is" etc.

Inform 7 looks like something I could teach my parents pretty easily.
Except that such a language probably makes you use real english subconciously and therefore will take longer to write because you're constantly correcting stuff :)
 
Last edited by a moderator:
That is what I meant. For most programmers and for most cases, ASM is useless as in "has no use". I thought the addition of "as ancient greek" would make that clear. Someone lerning programming will probably not just make stuff for embedded systems, not for years if ever, so for him, ASM would be useless.
I beg all those who love ASM pardon, I diddn't want to say that it is, for all purposes, useless.

Then you picked a very inappropriate analogy. While there's some practical reason to be able to read ancient Greek, there's no practical reason to be able to write it. This is hardly the case with assembly language. Maybe you didn't want to say that for all practical purposes it's useless but that's literally what you said.


I don't really know why you figure someone learning programming won't do embedded. It's arrogant to think they'll be doing whatever it is you do instead. As someone who "hates Java bashing" you should be more careful with what you say.
 
Back
Top