View Full Version : I want to learn some programming
xneoangel
September 19th, 2006, 05:10
As the title says "I want to learn some programming", but well i don't know nothing about it, so i'd like you guys to tell me with which programming language i should start and if you can tell me of some sites that have some documentation on that language so i can get started.
My goal is to make emulators, i should start with a Chip8 one but well i have to learn a programming language first so i should stop daydreaming for now :P
Toasty
September 19th, 2006, 05:56
C and C++ are good languages for writing emulators, but depending on how your brain works, you may or may not want to start out with one of them. I struggled for a long time trying to learn C and C++ when I first wanted to learn how to program, but I just didn't get it. At the time I already knew HTML and JavaScript (I knew how to script, but not program), so I stuck with those for a while. Eventually I finally took it upon myself to learn Java, and after a few months of confusion, the whole object-oriented concept clicked. I got to where I was comfortable writing in Java and then moved on to C#. After learning those two, I came back to C and C++ and they were very natural to me, since they shared many syntactic and conceptual similarities with my previously learned languages.
On the other hand, there are many people who pick up on C/C++ very quickly with no previous programming experience. Download a C++ compiler and IDE (Dev-C++ (http://bloodshed.net/devcpp.html) is free and easy to set up) and try one of the beginner C++ tutorials (Google (http://www.google.com/search?q=c%2B%2B+tutorial) for it). If you are having a hard time understanding what's going on you might want to try something different and then come back to C++ later.
aprentice
September 19th, 2006, 07:08
I started out with a DOS programming book for C. I didn't have to focus on windows specific code so I was able to pick up C quicker. I'd recommend a C programming book for DOS first if thats the language your interested in learning, it seemed a lot easier for me at least.
xneoangel
September 19th, 2006, 07:21
Ok i downloaded Dev-C++ and found a tutorial (http://www.cprogramming.com/tutorial.html#c++tutorial)tutorial which seems nice but well iom already having problems :( , there are some words which i don't understand like preprocessor and iostream, is there any site where i can find definitions of words like these i mentioned?
Hmmm i'd prefer to learn it on a windows environment since i only have basic knowledge of DOS, im 16 and i really never used it much so well that would mean to learn DOS as well which would be troublesome IMO, anyway thanks for your support.
EDIT: I found this definition of preprocessor.
In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program.
So lets see if i got it right.
#include <iostream>
So iostream would be the preprocessor right? so iostream will use its input data to produce an output which will be used as input data by the compiled program right?
So basically im telling the program to include iostream data in it right?
Toasty
September 19th, 2006, 08:05
#include<iostream> basically incorporates the header file, iostream into your program. iostream is part of the C++ standard library, and by including its contents in your program, you are able to use functions, definitions and classes in that file. All the lines that start with a # are preprocessor directives. The preprocessor makes intermediate changes to your code that you never have to see, but that the final compiler will see. #include basically means copy all the code from this file (in this case, iostream) into my file.
Suppose we have a header file of our own that looks like this (we'll name it "MyHeader.h"):
int MyAddFunction(int a, int b) {
return a + b;
}
And then we include it in your hello world program like so:
#include<iostream>
#include "MyHeader.h"
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
Basically, this tells the preprocessor to copy all the code from our header into this file. After the preprocessor does its work, the final compiler sees this:
/*The contents of iostream goes here, but it's way too long to post*/
int MyAddFunction(int a, int b) {
return a + b;
}
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
In essence, it's a way to virtually copy code into our source file without making the source file huge in the process, which makes code a lot more manageable. It's also handy when you want to use the same code in many different source files, which will be important in bigger programs. The reason the tutorial told you to include that file is because it contains the definition for cout (short for "console out", BTW), which you will use to print text to the console.
Garstyciuks
September 19th, 2006, 16:04
I started out with a DOS programming book for C. I didn't have to focus on windows specific code so I was able to pick up C quicker. I'd recommend a C programming book for DOS first if thats the language your interested in learning, it seemed a lot easier for me at least.
Hmm, I learned C++ after messing a lot with OpenGL at NeHe site (http://nehe.gamedev.net) :P The windows programming part came while programming my Chip8 emulator. I did some DOS programming, but in assembly.
xneoangel
September 19th, 2006, 16:13
In essence, it's a way to virtually copy code into our source file without making the source file huge in the process, which makes code a lot more manageable. It's also handy when you want to use the same code in many different source files, which will be important in bigger programs. The reason the tutorial told you to include that file is because it contains the definition for cout (short for "console out", BTW), which you will use to print text to the console.
Thanks now i got it. :D
Doomulation
September 19th, 2006, 18:09
C and C++ is very low level, thus it is generally not a good idea to start with a high level language like VB IMO, because you'll be all confused later.
Anyway, preprocessor is a co-compiler you might say that parses your source files before the compiler and does its work. There are a lot of preprocessor commands available, arguably the most used is the #include which, as explained, includes the contents of a file into the position where that is.
A good way would be to get a small taste for the language through console-based programs. Then, you would logically move up to Windows-based apps. Howver, Windows inner workings and its API is not easy. But it important to understand it even if you are using Frameworks such as MFC, ATL or WTL.
Use a tutorial, do it. Find another one, do it. And when you get stuck--ask. That is the way to learn. Now good luck.
xneoangel
September 19th, 2006, 18:18
Thanks now i understand what is a preprocessor. :D
I'll take your advice i'm gonna do the tutorials and ask if i get stuck...
The nice people here at emutalk are always great help.
Iconoclast
September 19th, 2006, 23:32
Yes! For once, I can learn this language because I can finally install the thing. Hard to install on a limited account until you gave me that link.
I'm new to C, as well, but I DO know ActionScript, up to Flash Player 6 in scripting complexity and some AS 2.0. I know a little HTML and even more DOS. I use DOS batch files to instantly start N64 games in Project64 and stuff, and I also use DOS when my PC shuts down at bedtime (a feature my parents installed), as I can't use Windows after 10 PM, but I can still use DOS even on Windows XP in a bootable floppy disk. That is why I like DOS emulators.
I also know FEN, but that's a chess setup 'programming' (not quite) language, so screw that.
Doomulation
September 19th, 2006, 23:35
While coding HTML, javascript & using DOS commands may give you a "Core User" title, you'll be surprised to find how little they can help or have in common with a real programming language of the scale of C/C++.
You may know a little about the whole art of programming, but you will find a lot of surprises about C/C++. It is not merely the language - but the way it works. You'll find that a lot of things go wrong and unlike javascript, the debugger won't tell you what is wrong, but what WENT wrong (ie, access violation at address 0xXXXXXXXX). The debugger will tell you WHAT went wrong but not WHERE or HOW. And often furthermore, you will find that it is not easy to figure out WHY either, because an access violation can mean many things.
Iconoclast
September 20th, 2006, 00:47
I see. In fact, I got an error right now. I figured, eh, I'll look into the tutorial of Dev-C++ later. I took a break, and decided to download the sourcecode for zilmar's No Sound plugin. What I REALLY wanted was the source for his Basic Input Plugin, but for some reason, NGEmu.com said it came with the sourcecode, but it didn't.
Anyway, I tried using Dev to open the file Audio.c of his sourcecode, and I try the Execute/Compile command to try to compile it (or how do I get this thing into a DLL?). Then I get this error, "dsound.h: No such file or directory." I saw the "#include <dsound.h>" paramater in the sourcecode, so I looked for the file in the Include subfolder of Dev-Cpp. I saw the other files needed, stdio.h and windows.h, but no dsound.h. Is this some sort of corrupt installation here, or am I missing something (most likely)? I even tried Googling about the error and trying to get the file using LimeWire, but none of the versions worked.
So, how do I successfully compile zilmar's sourcecode to the No Sound plugin?
Poobah
September 20th, 2006, 04:49
'dsound' is short for DirectSound. You'll need the DirectX SDK, but it just happens to be filled with about 400MB of extra stuff that you probably won't be wanting, so you should just download this one (http://alleg.sourceforge.net/files/dx80_mgw.zip). Extract it into the Dev directory that contains "bin", "include", etc.. You'll also have to include some libraries, but I don't do any DirectX programming, so someone else will have to tell you.
Does the source that you are trying to compile come with any DSP, DSW or VCPROJ files? Those are MSVC project-related files. I'm not sure if Dev-C++ can open those or not, but it would be preferable to compile using one of them.
Regarding C/C++ programming, I recommend that you start with C and then move on to C++. It's useful to learn C first because you'll get an understanding of some essential things such as how strings are stored and pointers. (You'll love pointers, by the way.)
I'm not sure if these will help you or not, but the following are the best C/C++ guides I've happened across:
http://lib.daemon.am/Books/C/
http://lib.daemon.am/Books/C++/
I could never get my head around C until I first got used to interrupts and other DOS stuff in QBASIC. The most off-putting thing for me was that there just isn't a nice and easy way to do graphics-related stuff unless you're writing DOS programs.
Iconoclast
September 20th, 2006, 04:59
Alright, I'll be looking at those links.
The zip you uploaded gives me a Page Cannot Be Displayed error.
Yes, it comes with No Sound.dps, dsw, ncb, and opt.
Doomulation
September 20th, 2006, 09:41
I figure you could start with either C or C++. You don't have to delve into anything advaced and C++ is C with some extensions so basically you can do either and start learning.
Dsound.h is part of the DirectX SDK, which you should consider getting if you want to create DirectX-based games. Oh and sorry to burst your bubble, but the sound plugin is way beyond your understanding as of still, I bet.
Iconoclast
September 21st, 2006, 00:50
I figure you could start with either C or C++. You don't have to delve into anything advaced and C++ is C with some extensions so basically you can do either and start learning.
Dsound.h is part of the DirectX SDK, which you should consider getting if you want to create DirectX-based games. Oh and sorry to burst your bubble, but the sound plugin is way beyond your understanding as of still, I bet.Yeah, I know it is. But I plan on learning as much as I can with my time, and I have the source for his No Sound plugin, and I just want the file Dsound.h, the whole DirectX SDK if it has other files I will also need for compiling them.
Still, even though I may never learn enough C or C++ to fully understand the sourcecodes of the plugins and emulators and make my own, maybe never get even near that, I still want the file. See, what I used to do, was I could use the MS-DOS Editor in Edit Binary mode to change the title bar and properties of N64 DLL plugins. Obviously, I can't really fully edit binary, but I could edit the parts that I could understand, such as the title/name of the plugin and About info, not to make it say I made it or anything so copyright-infringing.
Now I just wanted to get into seeing if I could learn how to better change these plugins, by downloading a compiler to try to see if I can edit some of what I want using their sourcecodes. So, I would still like the file (complete DirectX SDK in entirity, if necessary for other sourcecodes).
Also, where is the sourcecode for zilmar's Basic Input Plugin? Everywhere I go, it says "Open source" or "includes sourcecode," but when I open the archive, I only see the DLL.:ranting:
And I'll start out with C, but thanks for the info.
Poobah
September 21st, 2006, 08:40
Try out this link (http://alleg.sourceforge.net/files/dx80_mgw.zip) again. Sourceforge sometimes has problems, but the 400KB SDK is quicker to download than the bloated 400-500MB Microsoft one.
Is dev-C++ able to open any of those project files such as the dsp/dsw ones? If not, you should give another IDE such as Code::Blocks a go, because it can open most MSVC projects, so compiling other people's MSVC projects should be almost trivial. The site's currently down, but I'll post a link to today's build once it's up again.
I don't think Zilmar's Plug-in is open-source, despite what some are saying. You could take a look at the sources of other plug-ins.
Doomulation
September 21st, 2006, 08:56
I don't think Microsoft's SDKs are bloated. They may be big, but they contain documentation, libraries, header files and examples on how to create and compile DX apps.
Iconoclast
September 22nd, 2006, 01:15
Damn. I really wanted zilmar's sourcecode (he didn't make it open source?!?) for that Basic Input Plugin. Even the user aprentice posted that it was open source. You really sure he didn't release a sourcecode for it? It's probably the most crappiest input plugin out there, but I like its simplicity, and since the keys are predefined, that could be useful for some things I have in mind. I just want it for its simplicity. Not that I will know enough C to learn how to modify which keys do what, but possible....
And, thanks for your help. I got the files, now. I'll look at those tutorials you linked to, assuming you'd say they're better for learning C than the Help option that comes with Dev-Cpp.
*Edit: Your tutorial link didn't work.
Forbidden
You don't have permission to access /Books/C/index.html on this server.
ShizZy
September 22nd, 2006, 01:39
I believe Sculleatr wrote a step by step tutorial on how to write an input plugin for N64. Can't seem to find it though.
Poobah
September 22nd, 2006, 03:08
*Edit: Your tutorial link didn't work.
That's odd. I've attached the two books. (I have local mirrors of 'em.)
tye stik
September 22nd, 2006, 04:16
http://cplusplus.com/doc/tutorial/
Thats the one I started out with. I didn't understand some of it while I was doing it, but just skip it if you dont get it and start on the next section... comeback after learning something different. It helps me when I'm learning. It usually gives me a different perspective on a problem I'm having.
As for C++ coding... if a program dosent compile and run properly, look for basic syntax errors... theres been times where for hours I'd look for where I went wrong, only to find I missed a ; or a }. Total bummer. :P
xneoangel
September 23rd, 2006, 02:32
I'm having some advance in C++ coding, i have already played a bit with basic variables and strings, but well its weird in the tutorial i'm doing every sample program ends up with:
return 0;
i don't know what that commad does as the program works even if i dont put it at the end, so its kinda weird what does that line do?
And also since i'm starting i'm only making console based programs which display something on-screen but when i execute the program the program shows me the stuff but it dissapears instantly, is there a line of code i can introduce to put a dealy time of about 5 seconds before it closes or to close it only when i press the X button?
mudlord
September 23rd, 2006, 03:44
Essentially, that "return 0" statement, is used to return a program's status. When its status is "0", the program exists. Of course, there are other ways to clean up a program's CPU threads.
And there is code that can display a console window until the program is closed forcibly (like when using CTRL-ALT-DELETE or pressing the "X" button in Windows). When I get around to it, I'll post a code sample of how to do that :).
Toasty
September 23rd, 2006, 06:45
When your main function ends, that usually marks the end of your program's execution. Whenever a program exits, it returns a number to indicate the conditions it exited under. Zero indicates a successful, 'normal' shutdown. Other integers can indicate various errors that caused the program to terminate prematurely. Some compilers don't care whether you put 'return 0' at the end of your main function and will automatically do it for you, but it's good practice to explicitly return something when the function signature (in this case, int main()) says it will.
Iconoclast
September 23rd, 2006, 16:52
Nope. Still didn't work.
I got this log when I tried to compile Audio.c:
Compiler: Default compiler
Executing gcc.exe...
gcc.exe "E:\Utilities\Dev-Cpp\Projects\Audio.c" -o "E:\Utilities\Dev-Cpp\Projects\Audio.exe" -I"E:\Utilities\Dev-Cpp\include" -L"E:\Utilities\Dev-Cpp\lib"
In file included from E:\Utilities\Dev-Cpp\Projects\Audio.c:2:
E:/Utilities/Dev-Cpp/include/dsound.h:1888: error: redefinition of typedef 'LPDIRECTSOUNDFULLDUPLEX'
E:/Utilities/Dev-Cpp/include/dsound.h:175: error: previous declaration of 'LPDIRECTSOUNDFULLDUPLEX' was here
Execution terminated
And I replaced all the "include" files with those from your DirectX SDK, of course. Could this be the compiler, or did I screw up on something again?
Doomulation
September 23rd, 2006, 17:00
I'm having some advance in C++ coding, i have already played a bit with basic variables and strings, but well its weird in the tutorial i'm doing every sample program ends up with:
return 0;
i don't know what that commad does as the program works even if i dont put it at the end, so its kinda weird what does that line do?
And also since i'm starting i'm only making console based programs which display something on-screen but when i execute the program the program shows me the stuff but it dissapears instantly, is there a line of code i can introduce to put a dealy time of about 5 seconds before it closes or to close it only when i press the X button?
Here's the deal...
Return is the instructions that says end this function now and return. Each function needs to either return void or another type of value or class. The main function is typically int main (though some compiler can allow a void main I think, but that is not good practice).
Return 0 means return 0 and end this function. In code, a function can typically return whatever you want and you can pick that up later. When it comes to threads, the thread's entry function (in this case, main) [Note: This isn't really relevant, but main isn't the main entry function; there is another function before that calls main, but you don't have to remember this] returns the value you want the thread to end with. Programs can later pick up what number or return value a thread ended with.
Did you get all that? What you return from main is (usually) what other programs wants to check for for success or error. Your program does not necessarily have to return 0. It can return any value you want and there are no guidelines for this (And I sure do not recommend writing console apps that returns values to indicate success or failure, because that is DOS-nature, and we're now in Windows-nature. Instead, if you want to share functionality with other apps, make a dll).
xneoangel
September 23rd, 2006, 17:19
Ok so return (any value); basically gives the computer the value i selected to indicate the program worked ok and closes it?
Oh and do you know some code i can introduce in this console based apps so that i doesnt colse after it executes but when i close it manually?
Thanks for your help guys.
Doomulation
September 23rd, 2006, 17:22
Ok so return (any value); basically gives the computer the value i selected to indicate the program worked ok and closes it?
No, not exactly. The compiler only generates the code and the computer only follows instructions. When you return a value from main, it is what program that started your app that decides what to do with it. When you return a value from main, however, it is assumed that it means success or failure, but it mustn't be so.
Oh and do you know some code i can introduce in this console based apps so that i doesnt colse after it executes but when i close it manually?
Ah, yes forgot that!
Do something like...
int buf;
cin >> buf;
This tells it to wait for input and store it in buf. So just type something and press enter and it will then terminate the program.
xneoangel
September 23rd, 2006, 17:33
Ok now i got it.
Let me see if i understood your code.
int buf; //Defining a variable
cin >> buf; //Input something which will be stored in the buf variable
Am i right?
So because in the function you added an input it'll will only close after it finishes its function which is displaying the stuff i put in before that code and inputting something that will be stored in buf?(if it's a variable i can give it any name i want except reserved commands right?)
Doomulation
September 23rd, 2006, 17:37
Bravo. It will execute all your code 'til the end and will then wait for you to input something. After you do that, it will close.
Yes, because you store it in a variable, you can name it whatever. However, be careful. It's not usually a good idea to input into an int, becuase you never know if the user will type a string or a number. You'll have to go through a long process of clearing the input buffer or something which I don't remember. Better to use a string (char) and later convert it to a number if that's what you're expecting.
xneoangel
September 23rd, 2006, 17:48
Ok i got it.
Now i can finally see what i did for more than 0.2 seconds :P
mudlord
September 24th, 2006, 01:00
OK, here's a very simple console app. It is a sinewave synth, based on the BASS sound system. The program will exit when the spacebar is selected, and the program will only close when this happens or when it is forcibly closed.
I hope this app is a good enough practical example.
Iconoclast
September 24th, 2006, 01:48
Did any of you guys even try compiling the source for the No Sound plugin using Dev-Cpp?? I don't think it works. Might be the compiler, or that I replaced all of the files with those from the zip poobah uploaded instead of just dsound.h.
Well, I'm in Chapter 2 right now, and I'm very slowly intaking that tutorial, but I am finally learning C. Thanks for the link.
And thank you, mudlord, for your example. I'll study it right now.
Poobah
September 24th, 2006, 04:09
I think you are supposed to not replace the ones that already exist, because DX8 is pretty old and so MinGW would come with more recent headers, but I'm not sure if that is what was causing the problem.
Doomulation
September 24th, 2006, 13:36
The problem would probably be a) outdated headers or b) compiler problem.
Iconoclast
September 24th, 2006, 22:00
I just reinstalled it, got all my header files back, pasted ONLY the file dsound.h in the include directory, tried to compile the No Sound plugin, and I got this:
Compiler: Default compiler
Executing gcc.exe...
gcc.exe "E:\Utilities\Dev-Cpp\Projects\Audio.c" -o "E:\Utilities\Dev-Cpp\Projects\Audio.exe" -I"E:\Utilities\Dev-Cpp\include" -L"E:\Utilities\Dev-Cpp\lib"
In file included from E:\Utilities\Dev-Cpp\Projects\Audio.c:2:
E:/Utilities/Dev-Cpp/include/dsound.h:1888: error: redefinition of typedef 'LPDIRECTSOUNDFULLDUPLEX'
E:/Utilities/Dev-Cpp/include/dsound.h:175: error: previous declaration of 'LPDIRECTSOUNDFULLDUPLEX' was here
Execution terminated
It must be, like Doomulation said, either a) the dsound.h file I got from poobah, b) the compiler, or c) Damn salesman. I'm gettin' me mallet!
Doomulation
September 24th, 2006, 22:19
If you have a fast connection, try downloading the real DirectX SDK and see if it compiles with those headers.
Poobah
September 25th, 2006, 01:24
I don't think the official one works with MinGW. Maybe I'm mistaken, but I don't think that any of Microsoft's SDKs work with MinGW. I'll try compiling it myself and see if I can get it to work.
EDIT: Just comment out the redefinition of it and it should work fine. You'll need someone to translate the MSVC inline assembly code to use GCC syntax before you can compile it, because they're completely incompatible.
Toasty
September 25th, 2006, 06:05
It's a little late to mention now, but on Windows platforms (and maybe Unix as well?) you can also pause the execution of your program by calling system("pause") as an alternative to using cin >> x. This will print a nice little "Press any key to continue..." message too. Bare in mind that the behavior (or lack thereof) of that command can vary from platform-to-platform though, so use it with care. You might also want to take a look at the C (not C++) version of "hello world". I remember that the overloaded << and >> operators in the C++ version kind of confused me at first, but the C equivalent just uses plain old functions to print and read from the console. But it's just a suggestion; proceed however you like.
@Iconoclast: Any chance you could start your own thread? It's kind of confusing to have two conversations going on in the same thread.
xneoangel
September 25th, 2006, 19:30
Ok i'm kinda stuck with this code, can you guys help me a bit?
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > "; //i don't understand what the > "; part does
cin >> n;
while (n>0) {
cout << n << ", "; /*and this the other line i don't understand, i know what cout << n does but the << ", " part confuses me*/
--n;
}
cout << "FIRE!";
return 0;
}
Thanks Toasty the system("pause") command works like a charm.
Doomulation
September 25th, 2006, 19:34
cout outputs the text (or variables) that you specify to the screen. Double quotes (looks like this: ") indicates a string. You got that? Okay.
cout << "Enter the starting number > "; // Prints the string "Enter the starting number > " to the screen.
cout << n << ", "; // First print the value of variable n, then output the string ", " to the screen.
Again, I urge you to consider using string buffers for input via cin unless you want to mess with clearing buffers.
xneoangel
September 25th, 2006, 19:55
>_<, ok i'm a little embarassed, that was one stupid mistake.
Again, I urge you to consider using string buffers for input via cin unless you want to mess with clearing buffers.
By that you mean that i should store stuff in strings via cin instead of in variables?
Doomulation
September 25th, 2006, 20:10
By that you mean that i should store stuff in strings via cin instead of in variables?
That is correct. Have you tried inputting a string when using cin >> buf (which is an integer)? It will mess up big time. Therefore, I recommend using a buffer of chars, then you can later use atoi to convert to a number if you are expecting it.
And if the user did not enter a number, you can check for...
if (atoi(buf) == 0 && buf[0] != '0') // Error occoured. Perhaps the entered data is not a number?
xneoangel
September 26th, 2006, 04:16
Ok thanks.
Now i have another question, i'm doing the tutorial at www.cplusplus.com, but a friend of mine borrowed me these books, Sams-Teach Yourself C++ in 21 Days 2nd Edition, Sams-C++ Primer Plus Fourth Edition and McGrawHill-C++ from the ground up.
Now my question is, should i continue with the tutorial or stop it and start with one of these books?
Poobah
September 26th, 2006, 05:39
The 21 days one is the very same one I recommended and posted earlier, so I'd recommend that one. Since you have convenient access to both, you should see which ones you find the best and use those.
xneoangel
September 26th, 2006, 13:08
Yeah well C++ Primer plus and C++ from the ground up, seem like great books, the thing is that they are 800 pages long :plain:
And the 21 days one seems good to but it is outdated, it uses iostream.h instead of iostream and it doesn't use the namespace std, and well i dont know if there is anything else.
Doomulation
September 26th, 2006, 13:23
I don't think it matters. Your goal is to learn the language, which is probably what it will do.
When it comes to Windows programming you'll enter a whole new world and there is no book in the entire world that can explain everything.
Poobah
September 26th, 2006, 13:43
But it isn't too hard to pick up if you get the documentation from the platform SDK's downloader. I found that theForger's Win32 API tutorial (http://www.winprog.org/tutorial/) was very helpful for kick-starting me into Windows programming. A resource editor like ResEdit (http://www.resedit.net) also makes things a lot easier.
Doomulation
September 26th, 2006, 14:08
Win32 Programming is much harder than a bunch of simple tutorials. It requires you know such things as what deadlocks are, what message pumping is, how to handle the GUI and messagages, etc, and why other programs FREEZE when one program FREEZES and they've done nothing wrong. Ah yes, I forgot, that's Windows fault.
xneoangel
September 27th, 2006, 01:05
Ok i started wiht one book but well i'm stuck at this exercise:
Write a program to ask the user to enter a series of numbers. Print a message saying how many of the numbers are negative numbers.
It's about the if statement, but i don't know how to do that.
can you guys help me a bit here?
I can get the program to identify which numbers are negative and which are possitive... but to count how many are negative well that confuses me.
Toasty
September 27th, 2006, 02:01
Start out with something like this:
int numberOfNegatives = 0;
Then, every time you read a number from the user do something like this:
if(numberFromUser < 0) ++numberOfNegatives;
/* ++numberOfNegatives basically means numberOfNegatives = numberOfNegatives + 1 */
Then after you have read all of your numbers, print the value of numberOfNegatives.
Poobah
September 27th, 2006, 02:02
Win32 Programming is much harder than a bunch of simple tutorials. It requires you know such things as what deadlocks are, what message pumping is, how to handle the GUI and messagages, etc, and why other programs FREEZE when one program FREEZES and they've done nothing wrong. Ah yes, I forgot, that's Windows fault.
I found that it wasn't harder than a bunch of tutorials and the official documentation, but each to his own.
What's a deadlock in terms of the Win32 API?
xneoangel
September 27th, 2006, 02:19
Start out with something like this:
int numberOfNegatives = 0;
Then, every time you read a number from the user do something like this:
if(numberFromUser < 0) ++numberOfNegatives;
/* ++numberOfNegatives basically means numberOfNegatives = numberOfNegatives + 1 */
Then after you have read all of your numbers, print the value of numberOfNegatives.
Ok if i do something like this:
while (cin >> numberfromuser) // to have an undefined number of inputs in the variable
and then put the code you told me, will it add 1 to numberofnegatives per each negative number?
Because it isn't working, or maybe i did something wrong:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{int a, num = 0;
cout << "Write a series of numbers separated by spaces:" << endl;
while (cin >> a)
if (a<0)
{++num;
cout << num;}
else
{cout << "You didn't input any negative number" << endl;}
system("PAUSE");
return 0;}
Poobah
September 27th, 2006, 03:50
What's wrong with that code? It works fine for me. (You might want to use [php] tags so that the code you post is easier to read.)
xneoangel
September 27th, 2006, 04:04
Well yes it compiles, but it doesn't do what i thought it would do.
I need it count how many negative numbers i enter and then display that number but if let's say i write two negative numbers, the number it displays it's 12 and not 2.
Poobah
September 27th, 2006, 04:06
As I said earlier, it's working fine for me. Perhaps what is confusing you is that you forgot to output a new line character after displaying the number of negative numbers.
EDIT: Oh, I see. I was entering one number per line. You could change it to output the count after all the numbers have been entered, but adding the new line character should also be sufficient.
xneoangel
September 27th, 2006, 04:13
Hmm yes it kinda works but if i input 3 negative numbers i get 123 and if input 2 i get 12 is there a way to make it only display the last number? which is the number of negative digits, also if i input any positive number i get the You didn't input any negative number established in the if condition but i thought it'd only display it if i didn't input any negative numbers but it appears if there is any positive number, how can i fix that?
Toasty
September 27th, 2006, 04:15
The output doesn't look very pretty, but it does seem to produce a correct end result for me as well. For the sequence:
12 -4 6 7 -8
I got the output:
You didn't input any negative number
1You didn't input any negative number
You didn't input any negative number
2
It could use some refinement (I'd get rid of the "You didn't input any negative number" line and print endl after you print num), but it does the job.
xneoangel
September 27th, 2006, 04:25
Ok here is an updated version of the code
using std::cout;
using std::cin;
using std::endl;
int main()
{int a, num = 0;
cout << "Write a series of numbers separated by spaces:" << endl;
while (cin >> a)
if (a<0)
{++num;
cout << "You inputted " << num << " negative numbers" << endl;}
system("PAUSE");
return 0;}
If i input two negative numbers i get this result:
You inputted 1 negative numbers
You inputted 2 negative numbers
But i only want to get the second sentence which is the correct number of negative numbers i inputed.
Poobah
September 27th, 2006, 04:25
Hmm yes it kinda works but if i input 3 negative numbers i get 123 and if input 2 i get 12 is there a way to make it only display the last number? which is the number of negative digits, also if i input any positive number i get the You didn't input any negative number established but i thought it only display it if i didn't input any negative number but it appears if there is a positive number, how can i fix that?
Just remove "cout << num;", and insert "cout << num << endl;" after the while loop so that it only displays the count after you've finished. A positive number is a non-negative number, so, logically, the message will display. Are you concerned about it interpreting zero as being non-negative? Perhaps you could change the loop to be a 'do' loop, where it continues while ( a != 0 ).
EDIT: With the non-negatives thing, just make it display that message after the loop if the number of negatives is zero.
xneoangel
September 27th, 2006, 04:35
Hmm if i put the cout << num << endl; outside of the loop for some reason it doesnt display any number after inputting them.
Oh well i'm going to sleep i'll keep trying to fix it tomorrow.
Poobah
September 27th, 2006, 04:36
That would be because the loop isn't ending. Just input something that cin doesn't read, such as the letter 'j', and it'll end because it will have read zero characters. Remember that your loop is depending on the number of characters read by cin, since you have used, "while (cin >> a)".
Doomulation
September 27th, 2006, 09:28
What's a deadlock in terms of the Win32 API?
Deadlock means that your threads are waiting for something and therefore isn't responding. Indeed, deadlocks are very common and is a typical example what happens when one application freeze when ANOTHER application in the system has frozen.
Poobah
September 27th, 2006, 09:49
Oh, I see. I don't think those are as much of a problem as Windows' idiotic HDD thrashing and new task manager.
Doomulation
September 27th, 2006, 11:29
I would say on the contrary. Windows API is flawed and a number of things can cause your application to freeze because of it. And when you ship your application, people will blame YOU when it freezes, not Windows.
Concerning your code, let me post a sample of what I would do:
#include <iostream>
using namespace std; // Specifies that every function in the namespace std can be refered without using std::
int main()
{
int a, num = 0;
char buf[1000]; // It never hurts to allocate too much. It is unlikely a user will enter 999 characters into the input stream, which eleminates the buffer overrun risk.
cout << "Write a series of numbers separated by spaces: " << endl;
while(cin >> buf)
{
a = atoi(buf);
if (a == 0 && buf[0] != '0')
cout << "\nInvalid number!\n";
else if (a < 0)
++num;
else
cout << "\nYou didn't input any negative number!\n";
}
cout << "You entered " << num << " negative numbers! Have a nice day.\n";
system("PAUSE");
return 0;
}
xneoangel
September 27th, 2006, 20:22
Could you explain to me what does this part of your code do?
a = atoi(buf);
if (a == 0 && buf[0] != '0')
Garstyciuks
September 27th, 2006, 20:56
atoi function converts the inputed string into a number. And then if checks if a number was entered. If the converted number is 0 (that also may mean that the string had no number entered in it) and it also checks if the first character wasn't '0'. If it was, then the number entered is valid. Here's an example of invalid entered string:
//buf is "sasd124"
a = atoi(buf); //a is equal to zero 0
if (a==0 && buf[0] != '0') //buf[0] is not 0, it is 's', so that means that the string is not a valid number
other example, with valid string number:
//buf is "0"
a = atoi(buf); //a is equal to zero
if (a==0 && buf[0] != '0') //buf[0] is 0, so it is a valid number - 0
and third example:
//buf is "0123"
a = atoi(buf); //a is equal to 123
if (a==0 && buf[0] != '0') //a is not zero, so the if fails, a valid number was entered
Doomulation
September 27th, 2006, 21:58
To complicate things more, you can also write
if (a == 0 && *(char*)buf == '0') // Invalid number
:P
Assuming you know what that means. It's basic pointer manipulation. Don't know if you've schooled yourself with that.
xneoangel
September 27th, 2006, 22:25
I would say on the contrary. Windows API is flawed and a number of things can cause your application to freeze because of it. And when you ship your application, people will blame YOU when it freezes, not Windows.
Concerning your code, let me post a sample of what I would do:
#include <iostream>
using namespace std; // Specifies that every function in the namespace std can be refered without using std::
int main()
{
int a, num = 0;
char buf[1000]; // It never hurts to allocate too much. It is unlikely a user will enter 999 characters into the input stream, which eleminates the buffer overrun risk.
cout << "Write a series of numbers separated by spaces: " << endl;
while(cin >> buf)
{
a = atoi(buf);
if (a == 0 && buf[0] != '0')
cout << "\nInvalid number!\n";
else if (a < 0)
++num;
else
cout << "\nYou didn't input any negative number!\n";
}
cout << "You entered " << num << " negative numbers! Have a nice day.\n";
system("PAUSE");
return 0;
}
Hmm that code doesn't work for some reason i believe the problem resides in the while loop that has to be ended somehow or use another loop, oh well i'll leave it like that i'll come back to it when i have a bit more of experience.
No i don't know about pointers yes i'm still a newb.
Thanks.
Doomulation
September 27th, 2006, 22:28
I copied that from your original code. The question is: how do you want the program to end? Ask for 5 numbers? Ask until you enter a positive number? Or something? You never specified what you wanted it to do exactly.
xneoangel
September 27th, 2006, 22:39
Ok i want the program to ask the user to input a series of numbers separated by spaces, if user didn't input any negative number display a message that says you didn't input any negative number (ore something like it), and if you input negative numbers it should tell you how many negative numbers you inputted.
EDIT: i want it to end with
You inputted X negative numbers(if you actually input negative numbers)
or
You didn't input any negative number(if you don't input any negative number)
Then after either of those two messages display the
Press any key to continue...
and after pressing the key it should end.
Doomulation
September 27th, 2006, 22:50
Well, that's an entirely different approach. This requires some more advanced code. I propose something like this:
#include <iostream>
using namespace std;
int main()
{
char buf[1000];
int n;
int num_negative = 0;
char* p = buf;
cout << "Enter some numbers: ";
cin >> buf;
if (atoi(buf) == 0 && *(char*)buf != '0')
{
cout << "\nInvalid value entered! Try again.\n";
return 1;
}
for (; p < p + strlen(buf) + 1; )
{
n = atoi(p);
if (n < 0) num_negative++;
if (*p == '-') p++;
while (*p >= '0' && *p++ <= '9');
if (*p != ' ' && *p != 0)
{
cout << "\nEncountered junk in input. Enter your numbers properly!\n";
return 1;
}
}
cout << "You entered " << num_negative << " numbers!";
}
xneoangel
September 27th, 2006, 22:55
Well, that's an entirely different approach. This requires some more advanced code. I propose something like this:
#include <iostream>
using namespace std;
int main()
{
char buf[1000];
int n;
int num_negative = 0;
char* p = buf;
cout << "Enter some numbers: ";
cin >> buf;
if (atoi(buf) == 0 && *(char*)buf != '0')
{
cout << "\nInvalid value entered! Try again.\n";
return 1;
}
for (; p < p + strlen(buf) + 1; )
{
n = atoi(p);
if (n < 0) num_negative++;
if (*p == '-') p++;
while (*p >= '0' && *p++ <= '9');
if (*p != ' ' && *p != 0)
{
cout << "\nEncountered junk in input. Enter your numbers properly!\n";
return 1;
}
}
cout << "You entered " << num_negative << " numbers!";
}
Ok... now that confuses me, i'll save that code and try to understand it when i'm more advanced at programming.
Thanks for your help.
Doomulation
September 27th, 2006, 23:00
Updated code:
#include <iostream>
using namespace std;
int main()
{
char buf[1000];
int n;
int num_negative = 0;
char* p = buf;
char* pEnd;
cout << "Enter some numbers: ";
cin.get(buf, 1000);
if (atoi(buf) == 0 && *(char*)buf != '0')
{
cout << "Invalid value entered! Try again.\n";
system("PAUSE");
return 1;
}
for (pEnd = p + strlen(buf) + 1; p < pEnd; )
{
n = atoi(p);
if (n < 0) num_negative++;
if (*p == '-') p++;
while (*p >= '0' && *p <= '9') p++;
if (*p != ' ' && *p != 0)
{
cout << "Encountered junk in input. Enter your numbers properly!\n";
system("PAUSE");
return 1;
}
p++;
}
cout << "You entered " << num_negative << " negative number(s)!\n";
system("PAUSE");
return 0;
}
Tested and works.
I can, however, tell you what the code does. First, it asks for some numbers seperated by spaces. It then checks if it is a valid number entered by checking if atoi returns 0 (since it returns 0 on error) and also if the first character in the buffer is the number 0. If atoi returns 0 and the first number entered isn't 0, then an error occoured.
Then it uses pointers to access data. The variable p points to the current position in the buffer where it will read the next character. pEnd is used to point at the end of the buffer. That is the length of the string + 1 (since strings always have a 0 at the end of the string). It checks the current position against the end position and checks if it has passed the end of the used buffer. If it has, then terminate the loop.
Inside the loop, first aquire the number entered. Atoi will check the buffer (starting at the position pointed by p) until it reaches a non-number char and will then stop and returns the number prior to that char.
Then check if it is negative. If it is, the increase the num_negative variable by one.
The app will check if there is a minus sign in the buffer, which would indicate a negative number. If so, increase the read position by one.
Then it checks if the current character in the buffer at the read position is a number (its ASCII value is bigger or equal to 0 and is lower or equal to 9). If it is, then increase read position. If not, then terminate the loop.
Last it will make a sanity check to make sure the next character is a space. If it isn't, then you've entered some junk data.
Lastly, it increases the read position so that it won't read the space next time.
After the loop is done, it checks the number of negative numbers found and prints it to the user.
xneoangel
September 27th, 2006, 23:09
Wow. :drool:
Yes it works perfectly.
Now thanks man, i'll save that code and try to understand it later, right now it's way beyond me.
Doomulation
September 27th, 2006, 23:11
Read my description to see what it does to see if you can make any sense out of it ;)
xneoangel
September 27th, 2006, 23:24
Way to much information for my head to proccess seriously i'll try to understand it when i get more knowledge on operators and pointers, because right now i only know some really basic stuff.
Thanks for the explanation i'll store it in a nice .txt with the code to came back to it later.
Poobah
September 28th, 2006, 02:39
Updated code:
#include <iostream>
using namespace std;
int main()
{
char buf[1000];
int num_negative = 0;
char* p = buf;
char* pEnd;
cout << "Enter some numbers: ";
cin.get(buf, 1000);
for (p = buf, pEnd = buf + strlen( buf ); p < pEnd; )
{
while (*p == ' ' || *p == '\t' || *p == '\n') p++; //Skip spaces, tabs and new lines
if (atof(p) < 0) num_negative++;
while (*p >= '0' && *p <= '9' || *p == '-' || *p == '.') p++; //Read through the number
//If there isn't whitespace after the number then it must be junk!
if (*p != ' ' && *p != '\t' && *p != '\n' && *p != '\0')
{
cout << "Encountered junk in input. Enter your numbers properly!" << endl;
system("PAUSE");
return 1;
}
}
if (num_negative == 0)
cout << "You didn't enter any negative numbers!" << endl;
else
cout << "You entered " << num_negative << " negative number" << ( num_negative == 1 ? "" : "s" ) << "!" << endl;
system("PAUSE");
return 0;
}
I fixed a few problems, and hopefully this one is easier to read. That last cout checks to see if the number is one or not to see if an 's' should be appended, for correct English. :)
xneoangel
September 28th, 2006, 04:26
Ok.
Thanks, yes it's easier on my eyes.
But i still need more experience to understand it, so i have to keep going.
Doomulation
September 28th, 2006, 09:14
Hmm, you did think of a few things I didn't, but I doubt you can put a new line into the buffer without pasting it. Oh and btw, I use cin.get because usually cin >> buffer stops when reading spaces. Something to remember. Therefore I use cin.get to specify how much data to read.
Poobah
September 28th, 2006, 12:11
Hmm, you did think of a few things I didn't, but I doubt you can put a new line into the buffer without pasting it. Oh and btw, I use cin.get because usually cin >> buffer stops when reading spaces. Something to remember. Therefore I use cin.get to specify how much data to read.
I added the new-line check because it seems that if the text that I enter wraps to the next line, a new-line character is inserted into the buffer, and it is otherwise interpreted as "junk".
Doomulation
September 28th, 2006, 12:29
I see. Didn't know that.
pegasus001
September 28th, 2006, 12:51
well guys i think this exercise is kind of difficult for a begginer so i think it`s better for him to do things one step at a time and not to get confused with pointers or cin.get() things. For a better start let him enter the numbers separated by <enter>(new line) and specify a value like -50000 to stop the inputting. i think that easier for a begginer.
Poobah
September 28th, 2006, 14:06
I see. Didn't know that.
Actually, I was wrong about the wrapping thing. I must have added those new line checks while changing something else, and thought they fixed whatever was causing the "encountered junk in input" problem.
ShadowDamien
September 28th, 2006, 17:00
Meh, the only thing I program in is Visual Basic and Turbo Pascal. I'm not awesome at any of those either.
Doomulation
September 28th, 2006, 20:33
well guys i think this exercise is kind of difficult for a begginer so i think it`s better for him to do things one step at a time and not to get confused with pointers or cin.get() things. For a better start let him enter the numbers separated by <enter>(new line) and specify a value like -50000 to stop the inputting. i think that easier for a begginer.
Indeed, I most agree. However, the question was how to do it with spaces. If xneoangel will reformulate the question to inputting numbers after each other and an ENDING condition, I can rewrite the code to an easier one.
For example, quit after entering 5 numbers, etc.
pegasus001
September 29th, 2006, 11:54
i don`t know what books is xneoangel reading about c++, but i have a few ones for the absolute beginner, coz i guess that`s what he is. A good book i gained a lot of knowledge from about c++ is "c++ interactive course". I just learned it after some good programming in paskal. It only explains about classes, inheritance etc. and everything about oop. But i think that choosing c/c++ as your first programming language language is a bit tough. These languages are so low level that you`ll end leaving it, BUT THEY ARE AWSOME(if you master the beast named c++). I am currently programming in c#. My code has some elegance now but i miss the old days. So now i`m learning the stl. I know it`s a little tough but i bet it`s worth learning.
civilian0746
October 1st, 2006, 11:12
I agree with pegasus001. choosing c and c++ as first language is indeed tough. Because the the person would have a hard time understanding whats going on. They need to start with assembly and proper programming concepts. So they an take the understanding behind those high level languages like c for granted. Of course, even higher languages like C++ and vb becomes common sense when they grasp something like c.
Garstyciuks
October 1st, 2006, 11:54
I agree with pegasus001. choosing c and c++ as first language is indeed tough. Because the the person would have a hard time understanding whats going on. They need to start with assembly and proper programming concepts. So they an take the understanding behind those high level languages like c for granted. Of course, even higher languages like C++ and vb becomes common sense when they grasp something like c.
That totally depends from person who is trying to learn. I started from VB, then I learned a little of assembly programming and then C++.
Doomulation
October 1st, 2006, 12:44
I agree with pegasus001. choosing c and c++ as first language is indeed tough. Because the the person would have a hard time understanding whats going on. They need to start with assembly and proper programming concepts. So they an take the understanding behind those high level languages like c for granted. Of course, even higher languages like C++ and vb becomes common sense when they grasp something like c.
C++ IS C. Besides, assembly is EVEN harder than C or C++. Learn C/C++ first, THEN assembly. Of course, I do agree that every C/C++ programmer should know assembly, because it makes them know what goes on behind the scenes and therefore can do efficient coding and solve many of the hurdles.
civilian0746
October 1st, 2006, 15:20
How is assembly harder than c and c++? I reckon its simpler. It seems harder to someone if they are overconfident using higher level languages. But its quite plain, simple and universal. Its the ABCs of programming. People should know about assembly concepts and appreciate them before even attempting higher level languages. Its like starting to build a nuclear bomb without having any knowledge of nuclear physics. Their uncreative mind will always be full of holes and doubts and you get sick of them soon enough with all their stupid questions and problems.
Did he not say it himself that he wants to learn programming so that he can code from emus? He needs to know assembly upside down before anything else. Not only know...he needs to be an expert of assembly before he can even think about what he is trying to do. Because I doubt he will be writing emulators for ifs and elses and cins and couts and overloaded operators. Those complications don't exist in the realm he needs to be.
Doomulation
October 1st, 2006, 15:26
Learning all the opcodes isn't easy and it makes your code look messy and it's very hard to program and use it. Sure, it may be simple, but it makes everything else a pain: using jumps instead of ifs, pushing things in the right order to call a function...
And it usually is not PORTABLE.
My advice is: learn C or C++. Get aquianted with the language. Learn computer basics, such as memory and pointers. Then invest some knowledge into assembly. You probably won't write a whole program in assembly, so it isn't a key part.
civilian0746
October 1st, 2006, 16:32
lol...learning all the opcodes...nobody needs to learn all the opcodes. In assembly, they just need to learn different types so they can use them if required. Of course, that comes way way later after they have grasped all the assembly basics.
You are the one who said c and c++ are low level languages? I almost had a heartattack there when i read it. For you to say its messy and not portable, I guess you are overconfident with higher level languages as well. I don't see why its that hard. Its a pain to grasp those concepts once your mind is already corrupted with higher level shit. And you never really learn it completely after that. You feel like its a pain in the arse because you are used to lazyness on higher level languages. You feel like writing partial programs and inlining rather than writing proper code.
Of course, I am not saying he cant learn higher level languages. Of course he can. It took me less than 2 days to learn C++ including all its OO garbage. But I must admit, I spent most of that time looking up a descent tutorial that isnot full of those cin and cout garbage. I just could not bear the bit shifting operator overload hypocrisy. After that when I looked at java, the only thing i had to learn was that everything is pointers. I wonder how long its going to take for him. You still seem to be on the ABC stages. Does he feel confident enough to write real solutions? I dont think he even understood your last example all that well.
Doomulation
October 1st, 2006, 16:57
Oh please, it's obvious that you love assembly and hate everything else. Take a look around and ask expert whether they want to use assembly or C++. It's NOT garbage or crap or whatever. Many things can be MUCH, MUCH, MUCH easier in a high level language, that CANNOT be done in assembly. When working with objects, for example, you need to specify the offset.
You need to allocate data storage yourself. You need to pay heed to naming conventions (cdecl, stdcall, fastcall, etc). And so on.
C++ is NOT garbage, and assembly IS hard.
I don't want you to spout nonsense here. C/C++ IS hard, yes, and everyone needs time to learn. Can you do that in assembly without causing lots of confusion? I'd like to see you try.
civilian0746
October 2nd, 2006, 03:16
You should not speak nonosense here. There is nothing that can be done with higher level languages that can't be done in assembly. Otherwise those higher level concepts wouldnot exist. But there are things in assembly that cant be done with higher level languages alone. Assembly has facilities for working with everything you mentioned there as impossible. Classes/data structures/source organization...everything. You name it. Of course, it may require you to understand what they really are. But thats about it. The motive behind higher level languages does not include being easier than assembly so that people can ignore its teachings. Most of the things on those higher level languages come from lower level assembly programming concepts. You understand asembly, you can flawlessly understand anything. I don't see how people can call somoene an expert and not a newbie who thinks assembly is hard. I can see why you think assembly is hard. You said it yourself..."learning all the opcodes." The way you went about learning it is wrong. Its not like reading a novel that you can skip to the middle and figure out how it was in the begining. I am guessing you never tried learning it because you used the word "opcode." I seriously think you are going about the wrong way here. I saw an example of DirectSound somewhere. I mean wtf. He does not even understand sound and you are preaching him DirectSound. I don't mean to be offensive but he will get bored and loose interest in programming soon enough thinking its hard.
Toasty
October 2nd, 2006, 05:38
People should know about assembly concepts and appreciate them before even attempting higher level languages. Its like starting to build a nuclear bomb without having any knowledge of nuclear physics.
...or like breathing without intimate knowledge of the respiratory system! What an insane idea!
I'd rather not get involved in an X vs Y argument, but I learned to program (quite well if I do say so myself) in three different languages before I ever dabbled with assembly and I don't feel I missed out on anything because of it. Object-oriented concepts always fascinated me a lot more than line after line of individual instructions. There's a very human, natural way that C-like languages handle things that is lost in assembly. Code blocks, familiar operators, names, descriptive keywords, structures - IMO these all make C-like code a lot easier to read, write and understand than assembly.
pegasus001
October 2nd, 2006, 11:40
hey people don`t get so hasty now. We are only discussing. In my opinion assembly programming is harder. Not everyone one of us likes what`s going on behind the scenes, and sometimes is better. High level languages like those oop are made to make our life(the programmers) o lot more easier. I know by myself and by other programmers friend of mine that we are a so lazy class of mammals, so why do we have to write lots of lines of code just to make this : int x = y;
By the way i`m just learning about computer architecture to begin programming my own emu, can anyone of you gus tell me sth more.
PS. I also think assembly language is cool and i want to know what goes behind the scenes and i would like that everybody likes it too.
civilian0746
October 2nd, 2006, 15:44
...or like breathing without intimate knowledge of the respiratory system! What an insane idea!That would rather relate to "using programs without knowing how to code them." Not a logical extension.
Cyberman
October 2nd, 2006, 17:01
If you are curious what goes on behind the scenes you should look at the back end of GCC (IE get the source and examine what produces the code that links in). Or you should be able to produce assembler source from MS compilors still.
What's really interesting in what they produce when using compilor intrensics for MMX SSE and SSE2.
Cyb
Doomulation
October 2nd, 2006, 20:04
You should not speak nonosense here. There is nothing that can be done with higher level languages that can't be done in assembly. Otherwise those higher level concepts wouldnot exist. But there are things in assembly that cant be done with higher level languages alone. Assembly has facilities for working with everything you mentioned there as impossible. Classes/data structures/source organization...everything. You name it. Of course, it may require you to understand what they really are. But thats about it. The motive behind higher level languages does not include being easier than assembly so that people can ignore its teachings. Most of the things on those higher level languages come from lower level assembly programming concepts. You understand asembly, you can flawlessly understand anything. I don't see how people can call somoene an expert and not a newbie who thinks assembly is hard. I can see why you think assembly is hard. You said it yourself..."learning all the opcodes." The way you went about learning it is wrong. Its not like reading a novel that you can skip to the middle and figure out how it was in the begining. I am guessing you never tried learning it because you used the word "opcode." I seriously think you are going about the wrong way here. I saw an example of DirectSound somewhere. I mean wtf. He does not even understand sound and you are preaching him DirectSound. I don't mean to be offensive but he will get bored and loose interest in programming soon enough thinking its hard.
I have tried assembly. I even tried inlining all code in functions in assembly for maximum speed and how does it turn out? HARD, HARD, HARD. Not easy. Yes, all the opcodes... how to convert numbers... knowing where you put your data... in registers or in memory... Thankfully we can inline assembly and put it into vars...
Tell me, is it possible to create and use an object in assembly without using C/C++? No? Too bad. The high level languages also handles things for you, like allocating space, aligning, offsets, etc.
Again, you seem to find assembly easy, but we DO NOT. Therefore, it is a good thing to learn a high level language FIRST, then learn assembly well enough to learn what goes on behind the scenes when you encounter problems that need assembly knowledge to solve.
Actually, I have made a few assembly hacks, so don't tell me I don't know anything.
Toasty
October 2nd, 2006, 21:29
That would rather relate to "using programs without knowing how to code them." Not a logical extension.
If you choose to look at it that way, you may. (I see little difference between our illustrations.) However, there are thousands of successful programmers out there who have never touched assembly, so I think my point stands well enough on its own without an analogy. I thought assembly was neat when I was first learning about it, but when I discovered that the compiler could optimize just as well as I could about 99% of the time, I decided to go with the easier, less time-consuming option. Anyone who wants to try assembly as their first language is welcome to, but it definitely would have turned me off of programming right away.
civilian0746
October 3rd, 2006, 10:44
Yes, they are the ones who gets fired for asking their boss stupid questions like what stack overflow is. No! Only dumb ones who has no idea about what compilers do tries to optimise their code with assembly. Well, you learn that with assembly as well, how compilers do what they do. Thats not why people learn assembly. They learn assembly to learn how things work. So they can understand what everything is all about. If you don't know already, computers make up a really tiny portion of programmable devices and I would say more than half the programmers out there has never touched c/c++ for their work and 1/4 of them never associated themselves with it in their lifetime. I would say average microprocessor speed today is still around 12 mhz or less and industry loves to see assembly more than anything (actually there is something industry loves more...thats the next level down from assembly. Depends on the application and we dont refer to it as programming anymore at that level).
I have tried assembly. I even tried inlining all code in functions in assembly for maximum speed and how does it turn out? HARD, HARD, HARD. Not easy. Yes, all the opcodes... how to convert numbers... knowing where you put your data... in registers or in memory... Thankfully we can inline assembly and put it into vars...Apart from "all the opcodes," almost everything there is related to what you learn before you even start your hello world example. Actually, the hello world example in assembly is rather hard. Well, depends on the environment. If you are trying to write hello world on a lcd or something, you better be 3/4-expert in it before you even try. Beause you need to learn about semi advanced assembly concepts to do that. Assembly concepts are opcode independent. Those concepts apply equally for your home pc as well as your car. And no! For 99.99% of the cases, inline assembly is rather restricted to be of any use than making things worse. You are better off using your c or whatever compiler for them if you are trying to "optimise everything with assembly."
Tell me, is it possible to create and use an object in assembly without using C/C++? No? Too bad. The high level languages also handles things for you, like allocating space, aligning, offsets, etc.You should not answer to your own questions too soon. Its more than possible to create and use objects in assembly including doing everything like field alignment and memory allocation. If it was impossible with assembly, OOP programming would not exist. Of course, mannually and you don't learn assembly to do OOP.
Again, you seem to find assembly easy, but we DO NOT. Therefore, it is a good thing to learn a high level language FIRST, then learn assembly well enough to learn what goes on behind the scenes when you encounter problems that need assembly knowledge to solve.
Actually, I have made a few assembly hacks, so don't tell me I don't know anything.That last statement made me feel like you dont. You probably just learned some opcodes and patched your programs. I am guessing you did not get far by starting to learn in the middle.
Toasty
October 3rd, 2006, 12:01
Only dumb ones who has no idea about what compilers do tries to optimise their code with assembly.
In my experience, there's very little incentive to use assembly other than optimization, though that's not to say it's its only use.
If you don't know already, computers make up a really tiny portion of programmable devices
Enlighten me; what might one of those other devices be?
...and I would say more than half the programmers out there has never touched c/c++ for their work and 1/4 of them never associated themselves with it in their lifetime. I would say average microprocessor speed today is still around 12 mhz or less...
I would say that you say "I would say" too much. (Where are your facts?) Just because a programmer doesn't program in C/C++ doesn't mean that s/he does program in assembly.
...and industry loves to see assembly more than anything (actually there is something industry loves more...thats the next level down from assembly. Depends on the application and we dont refer to it as programming anymore at that level).
Which industry is this? Who's "we"? What's this next level down from assembly? It doesn't get much lower-level than directly hand-picking the instructions you want the CPU to execute. If you're not talking about programming then what purpose does the comment have in a programming thread?
Admittedly, there are some areas (writing code for extremely limited hardware, for example) where coding in assembly is a must. Hobby programming for modern PCs is not typically one of these areas. While eventually learning a little assembly will help a programmer to understand what goes on 'under the hood' it's much more likely to cause nothing but confusion and frustration if s/he jumps right into it in the beginning. I liked Wikipedia's subheading on the current usage of assembly language (http://en.wikipedia.org/wiki/Assembly_language#Current_usage). It summarizes what I'm trying to say very nicely.
civilian0746
October 3rd, 2006, 14:18
In my experience, there's very little incentive to use assembly other than optimization, though that's not to say it's its only use.Your experiance needs updating. I have rarely used and seen assembly on computers. Its totally not worth it. Even free compilers do better optimisations. And optimisation is rarely about faster code. There is no need to optimise "everything" to make things faster. In most cases, better algorithms can produce better results than those pityful assembly integration.
Enlighten me; what might one of those other devices be?Everything from missiles fired today to the ovens used for cooking are programable. I am sure the world does not change that much in a week but last week I went to buy a small speaker so I could do some experimentation with sound on my brand new Spartan-3 board (I am a hobbyist programmer as well) and was not surprised at all to find a huge section of programmable toys in the shop. Not only toys, they have stuff for big kids as well. Already made up my mind for the next couple of birthday presents I am going to give ^_^
I would say that you say "I would say" too much. (Where are your facts?) Just because a programmer doesn't program in C/C++ doesn't mean that s/he does program in assembly.I never said they do. It would not be hard to find people who would say "c is hard." Its not hard damnit. If I can do it, everyone can!
Which industry is this? Who's "we"? What's this next level down from assembly? It doesn't get much lower-level than directly hand-picking the instructions you want the CPU to execute. If you're not talking about programming then what purpose does the comment have in a programming thread?It does not? Think again! You might figure out something. It might not be called "programming" but what they do is still programming. Of course, they come out with proper computer engineering degree studying everything about computers and related systems than just a couple of programming languages and grade 12 algorithms.
Admittedly, there are some areas (writing code for extremely limited hardware, for example) where coding in assembly is a must. Hobby programming for modern PCs is not typically one of these areas. While eventually learning a little assembly will help a programmer to understand what goes on 'under the hood' it's much more likely to cause nothing but confusion and frustration if s/he jumps right into it in the beginning. I liked Wikipedia's subheading on the current usage of assembly language (http://en.wikipedia.org/wiki/Assembly_language#Current_usage). It summarizes what I'm trying to say very nicely. They arent "some." They are most areas. I have only one computer in my room. Everything else electronic from my mobile phone, pda, the loose chip on my arcade stick...to my calculator is programmable where I have the option to reprogram or inject sub-programs compiled from their native assembly code with proper tools. Of course, some of them have higher level scripting options in them as well but they are too slow if you want to do something like make a game for it.
I never considered wikipedia to be credible but it summarizes most of what I have to say:
* When a stand-alone binary executable is required, i.e. one that must execute without recourse to the run-time components or libraries associated with a high-level language;this is perhaps the most common situation
* When interacting directly with the hardware, e.g. in a device driver, or when using processor-specific instructions not exploited by or available to the compiler
* When extreme optimization is required, e.g. in an inner loop in a processor-intensive algorithm
* When a system with severe resource constraints (e.g. an embedded system) must be hand-coded to maximize the use of limited resources; but this is becoming lessmore common as processor price/performance improves
* When no high-level language exists, e.g. on a new or specialized processor <--most common case
Has a few glitches but good enough. Most c compilers Ive come across outside the world of computers suck badly. You can do better job with broken assembly. Still, c is not low level. If C is low level, the only things that deserves to be called high level are parsed languages like php and javascript which has outrageous higher level extensions. Even with java, the end code that is executed today is comparable to the time on c. I am not saying c does not have non-standard platform specific extensions. But you would need to understand its corresponding assembly concepts to be able to use them and still it would not be the same.
Doomulation
October 3rd, 2006, 16:00
It's pointless to argue, but I have sometimes used asm to get around C++ language limitations. Such as callback to either a function OR a function within a class all within the same function. It's not possible since C++ does not allow you to cast pointers to function a generic type like void (without assembly).
And again - not using inline asm makes things even more complicated. Asm is hard and I learned it only because of a little interest - not because of what you say. I have learned enough to make out some of what the compiler generates and it helps me in certain situations when something has gone awry and I can't see what it is from the C++ code.
Cyberman
October 3rd, 2006, 18:48
[mild mod mode on]
Toasty, your experience isn't likely what other peoples experience are, your real world is not the complete world nor does it encompass all knowledge. Please try to be a little more sensible in your thinking. Just because you (personally) have had little use of assembly, in the areas you work in doesn't mean that is the end all be all of experience and existance for the subject.
I am giving you a hint to stop being beligerant and actually listen. If something doesn't sit well, stop, sit back and think, do some research. Then think again before saying anything.
I personally AVOID using assembly myself but have used it extensively.
civilian0746 relax a bit, use less 'stress' filled words. This is NOT a bar room brawl both of you.
[/end mild mod mode]
Ok both of you are a bit out of control SO. I'm going to be nice and say to Toasty, you've gone out of your realm of understanding, do some research then DISCUSE the topic please. You seem to have experience with some things, but what you have said is enough to really give the idea you have no experience with anything less complicated than a modern game console, which is far more complicated than the PC's of the mid 80's.
With some devices assembly is prefered since you have < 1K program word space (http://www.microchip.com/ParamChartSearch/chart.aspx?branchID=1009&mid=10&lang=en&pageId=74). A good place to enlighten yourself a bit is Microchip (http://www.microchip.com)'s web page, and a few others, Intel (http://www.intel.com/design/mcs51/index.htm?iid=ipp_embed+micro_51_251&), Amd (http://www.amd.com/us-en/ConnectivitySolutions/ProductInformation/0,,50_2330,00.html), Freescale (http://www.freescale.com/), Zilog (http://www.zilog.com/), Philips Semi (now NXP) (http://www.nxp.com/products/microcontrollers/80c51/index.html), and Atmel (http://www.atmel.com/dyn/products/devices.asp?family_id=607). I'm no fan of Microchip but I've used there processors. You can use C with a lot of there CPU's (mcu's to be precise) and one will find that the uChip IDE and C is extremely capabable of low level functionality. In fact you can compile an entire program in C without an OS for it to run on. As I have done a myriad of times.
I've even built a PC-104 board using the AMD186ER (http://www.amd.com/us-en/ConnectivitySolutions/ProductInformation/0,,50_2330_8579_8606,00.html) a fake DOS (IE just enough to load the program in ROM) to run an HVAC system (Heating Ventilating and Air Conditioning).
Cyb
Toasty
October 3rd, 2006, 23:31
I apologize - it wasn't my intention to imply that everyone's experience was similar to mine. For the most part, I program as a hobby, which I'm guessing (correct me if I'm wrong) is the initial goal of the original poster. It looks like I got a little too wrapped up and forced you to go into 'mild mod mode', so I'm sorry about that, and also that I came across as hostile. :( I do and did admit that assembly has its uses (in some of which nothing else is even plausible) - like you pointed out; I just felt it would be confusing to a beginner.
@civilian0746: I won't perpetuate the debate, but in my own defence, those other programmable devices are what I would consider computers. (I guess that was a misunderstanding.) All in all, the way you came across just made me feel as though you were imposing opinion as fact (perhaps another misinterpretation by me). Since our discussion warranted moderation, I'll agree to disagree if you will. :P
civilian0746
October 4th, 2006, 02:45
It's pointless to argue, but I have sometimes used asm to get around C++ language limitations. Such as callback to either a function OR a function within a class all within the same function. It's not possible since C++ does not allow you to cast pointers to function a generic type like void (without assembly).
And again - not using inline asm makes things even more complicated. Asm is hard and I learned it only because of a little interest - not because of what you say. I have learned enough to make out some of what the compiler generates and it helps me in certain situations when something has gone awry and I can't see what it is from the C++ code.
I dont know what you mean by "a function within a class all within the same function" but I am preety sure it does not make sense in that formatting. As for rest, c++ is one of the languages that actually supports proper function pointers and callbacks to function is more than possible without assembly and even without any typecasting. Void isnot a generic type in c++. Void simply means nothing. Its size is 0. Its unusable even in assembly. The only reason you can have pointers to void is because all pointers have the same size equal to the size of machine's address regs and matters little about what it points to.
Doomulation
October 4th, 2006, 13:37
I dont know what you mean by "a function within a class all within the same function" but I am preety sure it does not make sense in that formatting. As for rest, c++ is one of the languages that actually supports proper function pointers and callbacks to function is more than possible without assembly and even without any typecasting. Void isnot a generic type in c++. Void simply means nothing. Its size is 0. Its unusable even in assembly. The only reason you can have pointers to void is because all pointers have the same size equal to the size of machine's address regs and matters little about what it points to.
Try to make a template function that accepts an argument of type T that is supposed to be a function pointer. In your code, however, calling a function or a class function (a function declared within a class) does not have the same syntax and therefore, the compiler WILL complain either way you do it, because it parses code that is not possible to execute.
template<typename Fnc, typename Class> void MyFunc(T fptr, T* pClass)
{
if (pClass == NULL) fptr(); // If it's a class function pointer, this fails
else (pClass->*fptr)(); // If it's a function pointer, this fails
}
I cannot cast the pointer to the correct type either, because I don't know what type it is. So either way, one of those lines WILL fail!
I can't cast a function pointer to type void* either, so I can't accept arguments as void*. Even if I could, I wouldn't know what type it was, so it would still be impossible.
Is this solvable? It sure is. With assembly. A hack.
civilian0746
October 4th, 2006, 17:33
Try to make a template function that accepts an argument of type T that is supposed to be a function pointer. In your code, however, calling a function or a class function (a function declared within a class) does not have the same syntax and therefore, the compiler WILL complain either way you do it, because it parses code that is not possible to execute.
template<typename Fnc, typename Class> void MyFunc(T fptr, T* pClass)
{
if (pClass == NULL) fptr(); // If it's a class function pointer, this fails
else (pClass->*fptr)(); // If it's a function pointer, this fails
}
I cannot cast the pointer to the correct type either, because I don't know what type it is. So either way, one of those lines WILL fail!
I can't cast a function pointer to type void* either, so I can't accept arguments as void*. Even if I could, I wouldn't know what type it was, so it would still be impossible.
Is this solvable? It sure is. With assembly. A hack.
Mods, please excuse the following section
[section to be excused]
That is the most retarded piece of code I have ever seen. You weren't trying extend beyond what you can do with c++, you were trying to cover your stupidty with more stupidity. Seriously, what do you smoke? I am sure its nothing as sane as weed.
[/section to be excused]
As for your problem, its easily fixed with overloading the templated function.
template<class T, class CLASS> void MyFunc(T fptr, CLASS* pClass)
{
(pClass->*fptr)();
}
//fptr_type_exceptional = your normal function pointer type
template<class T, class CLASS> void MyFunc(fptr_type_exceptional fptr, CLASS* pClass)
{
fptr();
}
Not a single cast there.
Doomulation
October 4th, 2006, 17:38
Excuse ME for saying this:
This is standard code which is NOT retarded and if I am retarded then YOU are retarded.
What is wrong with implementing callback? I don't want two functions for the same purpose: I want one.
I know full well of overloads but I do not WANT to use them, IF possible. With assembly, I don't have to.
civilian0746
October 5th, 2006, 03:34
Excuse ME for saying this:
This is standard code which is NOT retarded and if I am retarded then YOU are retarded.I never said you were. Thats not standard code. Thats the stupidest piece of thing someone could ever think of. None of the 2 lines you had within that fuction makes any sense whatsoever and will only work for a tiny ammount of cases even if c++ supported them and you managed to compile or hacked it with assembly. This is not only invalid, but even if it was valid, a rather retarded style of programming.
What is wrong with implementing callback? I don't want two functions for the same purpose: I want one.Its not 2 functions. They are template functions. In a nutshell, they are like macros. Compiler generates functions for all combinations of template parameters and it would not be surprising to have 10-20 versions of them in the final piece of code that is translated into assembly for compilation. If you are after smaller code, its a bad idea to use them anyway.
There is nothing wrong with implementing callbacks. But everything wrong with implementing retarded callbacks. What are you trying to achieve there anyway. I am sure what you had there translates to nothing but stupidity even in the assembly level.
I know full well of overloads but I do not WANT to use them, IF possible. With assembly, I don't have to.I know. Just in case things become faster without an extra conditional. Why would anyone want that. They rather do things the retarded way like yourself and do "assembly hacks."
zAlbee
October 5th, 2006, 10:42
@civilian0746: Look dude, cool it. It's clear that you have a lot of knowledge and experience, but that does not entitle you to blatantly insult other members. You can hide all you want under [mod-excusable] tags, but that does NOT stop you from offending people.
Which industry is this? Who's "we"? What's this next level down from assembly? It doesn't get much lower-level than directly hand-picking the instructions you want the CPU to execute. If you're not talking about programming then what purpose does the comment have in a programming thread?
It does not? Think again! You might figure out something. It might not be called "programming" but what they do is still programming. Of course, they come out with proper computer engineering degree studying everything about computers and related systems than just a couple of programming languages and grade 12 algorithms.
He's on about circuits, logic gates and the like (probably my jargon is incorrect, but I am not an engineer).
C is a high-level programming language (or not): It's not a friggin' binary classification of high/low or left/right or black/white. We all know where C sits in the spectrum. As far as I can tell, you would like to group C with high-level because it makes you feel better, knowing that "low-level" is an exclusive club where only you and other advanced ASM programmers can hang out.
Yes, they are the ones who gets fired for asking their boss stupid questions like what stack overflow is. No! Only dumb ones who has no idea about what compilers do tries to optimise their code with assembly. Well, you learn that with assembly as well, how compilers do what they do. Thats not why people learn assembly. They learn assembly to learn how things work. So they can understand what everything is all about.
Although this statement is ridiculously opinionated and offensive, I'm going to agree with you on this one. Any good programmer should have knowledge of computer achitecture and how shit works, and this includes knowing Assembly. Even if they don't start off with a clue, eventually anyone who is serious about programming must get interested in it at some point.
Whether you should learn ASM as a starting point? I don't think it matters. A newbie should start out learning with a guide that makes sense, on a language that encourages them. If ASM excites you, then congrats. But very likely if someone doesn't see any good progress with ASM or they "can't make useful programs," then they will lose interest. You said it yourself, "he will get bored and loose interest in programming soon enough thinking its hard." In any case, if you want to be a GOOD programmer, you will need to spend the time learning both the low level and the high level (which is most likely what you will be programming in). That's what separates the good programmer from the guy who gets fired (other than being intelligent); the order of learning doesn't matter, except for bragging rights.
This thread: should be split. This debate over the usefulness of Assembly has nothing to do with the xneoangel's request for programming help.
civilian0746
October 5th, 2006, 11:12
I don't mean to offend anyone. Please excuse me if anyone found something offensive. I think Doom needs to understand the motivation behind some higher level ideas so he can appreciate them properly.
Toasty
October 5th, 2006, 11:44
He's on about circuits, logic gates and the like (probably my jargon is incorrect, but I am not an engineer).
Thanks for clarifying. ;) I suspected he might be talking about something like that, but like I said, I didn't think it was really relevant to a programming topic. Hopefully I haven't come across as too big of a jerk in this thread; Cyberman's words cut me to the quick when he said I was outside of my realm of understanding. (For the record, I do understand this stuff quite well, but I guess a little too much attitude and some poorly chosen wording made me look like a ranting noob. :P)
Doomulation
October 5th, 2006, 14:23
I never said you were. Thats not standard code. Thats the stupidest piece of thing someone could ever think of. None of the 2 lines you had within that fuction makes any sense whatsoever and will only work for a tiny ammount of cases even if c++ supported them and you managed to compile or hacked it with assembly. This is not only invalid, but even if it was valid, a rather retarded style of programming.
Its not 2 functions. They are template functions. In a nutshell, they are like macros. Compiler generates functions for all combinations of template parameters and it would not be surprising to have 10-20 versions of them in the final piece of code that is translated into assembly for compilation. If you are after smaller code, its a bad idea to use them anyway.
There is nothing wrong with implementing callbacks. But everything wrong with implementing retarded callbacks. What are you trying to achieve there anyway. I am sure what you had there translates to nothing but stupidity even in the assembly level.
I know. Just in case things become faster without an extra conditional. Why would anyone want that. They rather do things the retarded way like yourself and do "assembly hacks."
Why is it retarded? I find it retarded that I can't call both a class function and a global function within the same function scope without using overloads. A class function pretty much just takes the address of the class as its first parameter.
And whatever you say, template or not, two functions are overloads even if the two does not make it into the source.
Also it's a question of style. I have sometimes used assembly simply because I find the C++ alternative annoying and want to get around it.
civilian0746
October 5th, 2006, 17:01
Why is it retarded? I find it retarded that I can't call both a class function and a global function within the same function scope without using overloads. A class function pretty much just takes the address of the class as its first parameter.
And whatever you say, template or not, two functions are overloads even if the two does not make it into the source.
It's retarded because it doesnot even make any logical sense. The following code is the same as the code you had there:
template<typename Fnc, typename Class> void MyFunc(T fptr, T* pClass)
{
(pClass->*fptr)();
}If it was not retarded, the following would have made sense since both are "functions" and pClass is merely a pointer.
Using simpler convention, consider a function that takes 2 numbers a and b and returns its result:
mult (a, b) = a * b
This works quite well for fields which can be casted to the real type for which the above function is defined. It would make sense to have something like:
z = mult(y, z) where x, y, z in R or N or I or Z
But how can you expect it to relate to something like class which are like special fields such higher dimentional numbers or say a set of polynomials. The following wouldnot make any sense at all:
z = mult(y, z) where x, y, z in C
Unless you define a special function to work on that special field, e.g. a overloaded function, there is no scope where this is possible. And when you define an overloaded function specialized for that field, it wont work for fields mentioned before. Hence it is retarded without overloads.
Not even going as far as that, even if you look in terms of c++ programming, you had the callback as a template type. I.e. its supposed to work with all types of template parameters. Hence something like "(pClass->*fptr)();" does not make sense to be in your templated function even if its a "class function pointer." Its a totally invalid use of template functions. Or I should rather say, "pure stupidity." If compilers could interpret your assembly hacks, I am sure it would not let something this stupid compile.
Also it's a question of style. I have sometimes used assembly simply because I find the C++ alternative annoying and want to get around it.Its not a question of style. If it was not retarded, it would have been there. Nothing stops you from using labels and goto in c++ even thou its considered bad style of programming because even thou its considered bad, its perfectly valid. What you did there was purely invalid. You can't treat specialized methods the same way as normal functions. Because they are totally different things. Looks like you did not even learn enough about C++ to figure out whats real. There is nothing in c++ standards that says they need to be the same. There is nothing in c++ standards that says it needs to be implemented like taking the address of the object as first parameter or saving the address in a predetermined register. It would not matter if the compiler generates code that saves the address of object in a special file and the method reads them back for usage. There are places where you would need assembly with c++ and something this retarded isnot just one of them. And no, I am not saying this just because its not in the wikipedia list.
Doomulation
October 5th, 2006, 17:13
Let's just say I don't get your arguments 100% and I don't care really. I tend to use Goto in my code because, even though it is considered Evil(TM), I find it very useful. And does it matter HOW you do it, as long as the result is the same?
Tell me, how would you make a function that generates a new thread that starts in a function in a class of your choice (OR simply a function of your choice and no class). It would also take one optional argument of YOUR CHOICE. How would you do this? I would use a template function to get class, function and argument. Then I would use assembly and put the class offset into ecx (as defined by the msvc compiler) and call the function. I would also, of course, push the optional param onto the stack so that the function finds it.
If I should simply use a function that makes a thread that starts in function in your class of choice, I could it without assembly, with C++ standard techniques.
(pClass->*pFnc)(pParam);
Is this code retarded? And if it is, then how would you do it?
Oh and, I can't say I've learned everything by the book. I have always taught myself most of things and always went my own way.
civilian0746
October 5th, 2006, 19:08
Let's just say I don't get your arguments 100% and I don't care really. I tend to use Goto in my code because, even though it is considered Evil(TM), I find it very useful. And does it matter HOW you do it, as long as the result is the same?
Tell me, how would you make a function that generates a new thread that starts in a function in a class of your choice (OR simply a function of your choice and no class). It would also take one optional argument of YOUR CHOICE. How would you do this? I would use a template function to get class, function and argument. Then I would use assembly and put the class offset into ecx (as defined by the msvc compiler) and call the function. I would also, of course, push the optional param onto the stack so that the function finds it.
If I should simply use a function that makes a thread that starts in function in your class of choice, I could it without assembly, with C++ standard techniques.
(pClass->*pFnc)(pParam);
Is this code retarded? And if it is, then how would you do it?
Oh and, I can't say I've learned everything by the book. I have always taught myself most of things and always went my own way.
Same here. I've tought myself as well ^_^. Its really funny but I am yet to get myself a proper programming book. The only programming book I have is this book on file structures written in 1992 which i bough from some junk book shop from $5 (bought with 2 other books...total was $15). It has some interesting info on how HD organizes stuff but is irrrelevent I guess. I've always considered them as nothing more than waste of money and is only good for stating the obvious.
As for your problem, here is a solution. Compiles fine with msvc++ 8.0. Don't know how gcc handles methods. Look at it carefully, you might learn something obvious:
#include "stdio.h"
#include "windows.h"
//modified java style declaration for classes since they are different...
class ThrParent {
public:
//int ThrProc(void* lpParameter){return 0;}
};
//standard declaration we will accept for thread procs
typedef int (__stdcall * ThrProcNormalFcnType)(void*);
typedef int (__thiscall ThrParent:: *ThrProc) (void*);
//a sample structure to Handle thread data
struct ThreadData {
union {
ThrParent * clas;
void * ClassAddr;
} base;
union {
ThrProc cfcn;
ThrProcNormalFcnType nfcn;
void * vptr;
} func;
void * parameter;
};
//main thread procedure
DWORD WINAPI ThreadProc(LPVOID lpParameter){
ThreadData * data = (ThreadData *)lpParameter;
if (data->base.ClassAddr==0)
return (*data->func.nfcn)(data->parameter);
else
return (data->base.clas->*data->func.cfcn)(data->parameter);
}
/*
a var for last thread info...if you come across the possiblity of creating
multiple threads at the same time from multiple threads that there might
overwrite uncreated thread data, replace it with a threa safe list.
*/
ThreadData LastThreadInfo;
//the thread creation function
//assumption: parameter tParent will be 0 if its not a class
template<class CLASS, class FCN_CLASS> void CreateThr(CLASS * tParent, FCN_CLASS function, void * lpParameter) {
union {
FCN_CLASS f;
ThrProcNormalFcnType v;
};
union {
CLASS * c;
ThrParent * vc;
};
f = function;
c = tParent;
LastThreadInfo.base.clas = vc;
LastThreadInfo.func.nfcn = v;
LastThreadInfo.parameter = lpParameter;
DWORD t;
CreateThread(0, 0, &ThreadProc, &LastThreadInfo, 0, &t);
}
//a normal function
int __stdcall RandomprocedureCall(void * string) {
printf("String is %s\n", string);
return 0;
}
//a class and its thread function
class RandomClassProcCallExample {
public:
int ThrProcExample (void* lpParameter);
};
int RandomClassProcCallExample::ThrProcExamp le (void* lpParameter){
printf("String is %s\n", lpParameter);
return 0;
}
//code entry point
int main(){
printf("Start\n");
//first create a normal thread
CreateThr<RandomClassProcCallExample, ThrProcNormalFcnType>(0, RandomprocedureCall, "Die! Just Die!");
//wait for a while since we used LastThreadInfo instead of a proper list
Sleep(500);
//class thread
RandomClassProcCallExample x;
CreateThr<RandomClassProcCallExample, ThrProc>(&x, (ThrProc)&RandomClassProcCallExample::ThrProcExamp le, "This is inside a class");
Sleep(500);
printf("End\n");
}
Process both function type and method type parameters. Replace the __stdcalls with whatever calling convention you want your callback functions to use. No assembly needed ^_^.
Doomulation
October 5th, 2006, 19:13
Interesting... I'll have a look at this. Note that it accepts a void* arguments, which means that you can't have a function declaration which accepts an argument with anything else than void*.
UPDATE:
After studying it a little, I think I grasp what you're doing.
You're basically using a dummy class to define a pointer to a class in the thread structure... you're basically using unions (can't say I know much about them) so that data will duplicated into different types of pointers. That way, you could have a class function pointer and a global function pointer with the same address. That way, all you need is check if we're doing a class callback or not, then access the appropriate struct members...
Of course, when calling the new thread procedure, you simply cast the class function to the class function pointer for your dummy class...
I never would have thought that way. It shows that it works if you think hard enough.
But I can't say that it's much better than assembly, because this is pretty much stretching the language to its limits. It's in no way a standard procedure and is very dangerous.
civilian0746
October 5th, 2006, 19:23
void* is but another pointer. You can cast it to any other pointer types. Excuse some extra codes that might be in there. In the begining I tried to do everything with classes.
Doomulation
October 5th, 2006, 19:35
I know it is, but if the thread creator procedure takes a void* pointer, then it doesn't know what type it was from the beginning and thus the callback MUST take a void* as argument. IF you used a template argument instead, it could pass it right on and you don't need to cast your arguments back and forth.
civilian0746
October 6th, 2006, 02:54
Well, it does not need to. Its a secret between the person who calls the thread creation function and the thread callback function/method ^_^. It would not make much of a difference if you supplied a number as void*. Personally, I dont like fat function calls.
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.