As was foretold, we've added advertisements to the forums! If you have questions, or if you encounter any bugs, please visit this thread: https://forums.penny-arcade.com/discussion/240191/forum-advertisement-faq-and-reports-thread/
We're funding a new Acquisitions Incorporated series on Kickstarter right now! Check it out at https://www.kickstarter.com/projects/pennyarcade/acquisitions-incorporated-the-series-2

The beginner programming thread

1505153555663

Posts

  • ASimPersonASimPerson Cold... and hard.Registered User regular
    edited October 2008
    I just have to share this delicious piece of code somebody posted on Gamedev.net:
    int Add(int x, int y)
    {
    	char *p = 0;
    
    	return (int)&x[&p[y]];
    }
    
    int main()
    {
    	int eight = Add(5, 3);
    
    	return 0;
    }
    

    Kudos to anyone who figures out exactly how this works without reading the following info about array syntax:
    All that is required syntactically is that one of the expressions (eg the 5 or "array" in array[5]) be of pointer type and the other be of integral type - which is which doesn't matter. Thus the integral value could be before the brackets and the pointer value could be in the brackets, like 5[array]

    I know the hint but I don't really know why this works. The *p seems superfluous to me but I can't figure out how to get this working without it.

    Weirder still, &x[y] will give you whatever your program previously output!

    ASimPerson on
  • His CorkinessHis Corkiness Registered User regular
    edited October 2008
    ASimPerson wrote: »
    I just have to share this delicious piece of code somebody posted on Gamedev.net:
    int Add(int x, int y)
    {
    	char *p = 0;
    
    	return (int)&x[&p[y]];
    }
    
    int main()
    {
    	int eight = Add(5, 3);
    
    	return 0;
    }
    

    Kudos to anyone who figures out exactly how this works without reading the following info about array syntax:
    All that is required syntactically is that one of the expressions (eg the 5 or "array" in array[5]) be of pointer type and the other be of integral type - which is which doesn't matter. Thus the integral value could be before the brackets and the pointer value could be in the brackets, like 5[array]

    I know the hint but I don't really know why this works. The *p seems superfluous to me but I can't figure out how to get this working without it.

    Weirder still, &x[y] will give you whatever your program previously output!
    p[y] indexes 3 bytes past 0x00000000, we then & it to give us a pointer to 0x00000003. We then index x (5) bytes past 0x00000003, and & it giving us a pointer to 0x00000008. We then cast that into the integer 8.

    His Corkiness on
  • ASimPersonASimPerson Cold... and hard.Registered User regular
    edited October 2008
    ASimPerson wrote: »
    I just have to share this delicious piece of code somebody posted on Gamedev.net:
    int Add(int x, int y)
    {
    	char *p = 0;
    
    	return (int)&x[&p[y]];
    }
    
    int main()
    {
    	int eight = Add(5, 3);
    
    	return 0;
    }
    

    Kudos to anyone who figures out exactly how this works without reading the following info about array syntax:
    All that is required syntactically is that one of the expressions (eg the 5 or "array" in array[5]) be of pointer type and the other be of integral type - which is which doesn't matter. Thus the integral value could be before the brackets and the pointer value could be in the brackets, like 5[array]

    I know the hint but I don't really know why this works. The *p seems superfluous to me but I can't figure out how to get this working without it.

    Weirder still, &x[y] will give you whatever your program previously output!
    p[y] indexes 3 bytes past 0x00000000, we then & it to give us a pointer to 0x00000003. We then index x (5) bytes past 0x00000003, and & it giving us a pointer to 0x00000008. We then cast that into the integer 8.
    Ah, see now. I never really thought about the order of operations situation here, but [] is evaluated before &. With parens it would look something like this, right?
    &(x[&(p[y])])
    So you can't get rid of *p since it is essential to the whole trick working.

    What I should have done is think about the array operator like this:
    x[5] == *(x+5)
    Then the "trick" above makes sense. Let's completely expand it out:
    p[y] == *(p+y)
    &p[y] == &*(p+y)
    x[&p[y]] == *(x+(&*(p+y)))
    &x[&p[y]] == &*(x+(&*(p+y)))
    So if we cancel everything out:
    x+(p+y) == x+y

    Damn, that is some trickery.

    Stuff like this is why I simultaneously love and hate C.

    ASimPerson on
  • ecco the dolphinecco the dolphin Registered User regular
    edited October 2008
    ASimPerson wrote: »
    Ah, see now. I never really thought about the order of operations situation here, but [] is evaluated before &. With parens it would look something like this, right?
    &(x[&(p[y])])
    So you can't get rid of *p since it is essential to the whole trick working.

    What I should have done is think about the array operator like this:
    x[5] == *(x+5)
    Then the "trick" above makes sense. Let's completely expand it out:
    p[y] == *(p+y)
    &p[y] == &*(p+y)
    x[&p[y]] == *(x+(&*(p+y)))
    &x[&p[y]] == &*(x+(&*(p+y)))
    So if we cancel everything out:
    x+(p+y) == x+y

    Damn, that is some trickery.

    Stuff like this is why I simultaneously love and hate C.

    Good lords. Hear that cracking sound?

    That was my mind, breaking as it tried to wrap itself around that trick.

    ecco the dolphin on
    Penny Arcade Developers at PADev.net.
  • LittleBootsLittleBoots Registered User regular
    edited October 2008
    ASimPerson wrote: »
    ASimPerson wrote: »
    I just have to share this delicious piece of code somebody posted on Gamedev.net:
    int Add(int x, int y)
    {
    	char *p = 0;
    
    	return (int)&x[&p[y]];
    }
    
    int main()
    {
    	int eight = Add(5, 3);
    
    	return 0;
    }
    

    Kudos to anyone who figures out exactly how this works without reading the following info about array syntax:
    All that is required syntactically is that one of the expressions (eg the 5 or "array" in array[5]) be of pointer type and the other be of integral type - which is which doesn't matter. Thus the integral value could be before the brackets and the pointer value could be in the brackets, like 5[array]

    I know the hint but I don't really know why this works. The *p seems superfluous to me but I can't figure out how to get this working without it.

    Weirder still, &x[y] will give you whatever your program previously output!
    p[y] indexes 3 bytes past 0x00000000, we then & it to give us a pointer to 0x00000003. We then index x (5) bytes past 0x00000003, and & it giving us a pointer to 0x00000008. We then cast that into the integer 8.
    Ah, see now. I never really thought about the order of operations situation here, but [] is evaluated before &. With parens it would look something like this, right?
    &(x[&(p[y])])
    So you can't get rid of *p since it is essential to the whole trick working.

    What I should have done is think about the array operator like this:
    x[5] == *(x+5)
    Then the "trick" above makes sense. Let's completely expand it out:
    p[y] == *(p+y)
    &p[y] == &*(p+y)
    x[&p[y]] == *(x+(&*(p+y)))
    &x[&p[y]] == &*(x+(&*(p+y)))
    So if we cancel everything out:
    x+(p+y) == x+y

    Damn, that is some trickery.

    Stuff like this is why I simultaneously love and hate C.

    I can make a program that says "boobs"

    LittleBoots on

    Tofu wrote: Here be Littleboots, destroyer of threads and master of drunkposting.
  • AiranAiran Registered User regular
    edited October 2008
    I'm currently learning how to draw graphics using OpenGL when I discover that Microsoft have handily not updated the OpenGL files since version 1.1. Does anyone know how to do this (or link me to a guide) in Visual Studio C++ Express 2008?

    [edit] Or just Windows. I read MinGW provides up-to-date header files?
    [editx2]Never mind, I'm going the dualboot Ubuntu route. This seems to be a major headache to solve in Windows.

    Airan on
    paDudSig.jpg
  • NightslyrNightslyr Registered User regular
    edited October 2008
    I know I asked this before, but I can't find the posts that answered me, and I just want to make sure I'm on the right track anyway, so I'll ask again:

    The most important class in my game is the PlayerCharacter class. It's essentially a container class. Its properties are both simple types (ints, floats, strings) and other objects (loot, equipment, special attacks). I need to be able to store all this info somewhere. I'm thinking that the database is the best way to go.

    Given the complexity of the situation (objects containing lists of other objects), am I correct in thinking I need some sort of ORM system in place to handle the heavy lifting? If so, what would be the best solution? I think someone mentioned that LINQ can be used to do some ORM stuff, but from what's in my book, that's not exactly an ideal method. My biggest concern is in storing the loot and equipment a character has. These objects are decorators containing simple base loot/equipment objects, so I'm unsure as to how to store/retrieve them in an efficient manner.

    I believe someone gave me a link to some decent ORM code/software to look at, but I lost it. If I could get it again, It'd be greatly appreciated. This is for ASP.NET/C# 3.5.

    Thanks!

    EDIT: While I'm here, does anyone have any tips in using images with a liquid (percentage-based) layout? I need to use images for my main navigation because of the font I want to use. The font itself isn't too fancy, but I'm not 100% guaranteed that it's installed on everyone's computer. I want to use images as a background for each actual link, but since the navigation area's size isn't fixed, I'm unsure as to how I would ensure that the images aren't truncated. Let me know if I'm not being clear on what my issue is.

    Nightslyr on
    PSN/XBL/Nintendo/Origin/Steam: Nightslyr 3DS: 1607-1682-2948
    Switch: SW-3515-0057-3813 FF XIV: Q'vehn Tia
  • LoneIgadzraLoneIgadzra Registered User regular
    edited October 2008
    Airan wrote: »
    I'm currently learning how to draw graphics using OpenGL when I discover that Microsoft have handily not updated the OpenGL files since version 1.1. Does anyone know how to do this (or link me to a guide) in Visual Studio C++ Express 2008?

    [edit] Or just Windows. I read MinGW provides up-to-date header files?
    [editx2]Never mind, I'm going the dualboot Ubuntu route. This seems to be a major headache to solve in Windows.

    I used SDL+MinGW, worked pretty good. But I wasn't exceeding OpenGL 1.1 functionality so my program compiled in Visual C++ too, and I definitely preferred that IDE (code::blocks has some really incoherent configuration dialogs).

    LoneIgadzra on
  • urahonkyurahonky Registered User regular
    edited October 2008
    ASimPerson wrote: »
    Malyonsus wrote: »
    Oh snap. LC-3. That's what our CS oriented assembler class used. It was alright, but the fact that our teacher made us write our program in fake binary for the first half of the course soured me on the whole thing.

    I don't even understand why we had to do it for so long. It's like, yes I get that in real life assembly code can basically be directly converted to a binary sequence.

    Yeah, this is exactly why we did one lab and one homework assignment on "machine" code, since you're basically just asking the students to mechanically convert the assembly to "binary" anyway.

    Yeah our first program was to read through this binary code and figure out what the password for the program was. It was a little overwhelming at first, but now if I looked at it, I could figure it out in a few minutes.

    urahonky on
  • urahonkyurahonky Registered User regular
    edited October 2008
    Out of curiosity: How many of you listen to music while you program? If you do, what type of music? I tend to put on either Techno or Ambient because of the lack of words. That way I'm not focusing on them.

    My girlfriend thought it was weird that I was listening to music while programming last night. She said she wouldn't be able to concentrate.

    urahonky on
  • NightslyrNightslyr Registered User regular
    edited October 2008
    urahonky wrote: »
    Out of curiosity: How many of you listen to music while you program? If you do, what type of music? I tend to put on either Techno or Ambient because of the lack of words. That way I'm not focusing on them.

    My girlfriend thought it was weird that I was listening to music while programming last night. She said she wouldn't be able to concentrate.

    No, no music for me. I tried it once, but I wound up rocking out instead of programming.

    Nightslyr on
    PSN/XBL/Nintendo/Origin/Steam: Nightslyr 3DS: 1607-1682-2948
    Switch: SW-3515-0057-3813 FF XIV: Q'vehn Tia
  • urahonkyurahonky Registered User regular
    edited October 2008
    Nightslyr wrote: »
    urahonky wrote: »
    Out of curiosity: How many of you listen to music while you program? If you do, what type of music? I tend to put on either Techno or Ambient because of the lack of words. That way I'm not focusing on them.

    My girlfriend thought it was weird that I was listening to music while programming last night. She said she wouldn't be able to concentrate.

    No, no music for me. I tried it once, but I wound up rocking out instead of programming.

    Really? Hmm. Man... I find that odd. But I guess I don't do quietness very well. :P

    urahonky on
  • ecco the dolphinecco the dolphin Registered User regular
    edited October 2008
    urahonky wrote: »
    Out of curiosity: How many of you listen to music while you program? If you do, what type of music? I tend to put on either Techno or Ambient because of the lack of words. That way I'm not focusing on them.

    My girlfriend thought it was weird that I was listening to music while programming last night. She said she wouldn't be able to concentrate.

    I'll say only if I don't get ostracised for it. Please don't judge out loud.

    I uhh... listen to... mmm... music from decades past - Bonnie Tyler and Meat Loaf, say. Yeah there are lyrics, but I know the songs well enough that I end up ignoring them.

    ecco the dolphin on
    Penny Arcade Developers at PADev.net.
  • urahonkyurahonky Registered User regular
    edited October 2008
    urahonky wrote: »
    Out of curiosity: How many of you listen to music while you program? If you do, what type of music? I tend to put on either Techno or Ambient because of the lack of words. That way I'm not focusing on them.

    My girlfriend thought it was weird that I was listening to music while programming last night. She said she wouldn't be able to concentrate.

    I'll say only if I don't get ostracised for it. Please don't judge out loud.

    I uhh... listen to... mmm... music from decades past - Bonnie Tyler and Meat Loaf, say. Yeah there are lyrics, but I know the songs well enough that I end up ignoring them.

    Oh that's not bad.

    As long as it isn't Aqua or Hansen or something.

    urahonky on
  • quovadis13quovadis13 Registered User regular
    edited October 2008
    Continuing on with my great programming escapades. I am trying a new approach now and I need help with it.


    I have a C++ program and I need it to interact with other text files on a Unix system. I am now going to have the program hold up and wait in the middle for the text files to actually be created/updated. I am asking for help in writing some code that will cause the program to wait until all the necessary files are created.

    I am thinking that the best way to do this is have the C++ code wait for a new text file to update. How do I write the code that will make the program wait until this file is updated and then proceed as planned? I have been looking up the wait() command, but I am still a little bit confused. Some links or at least a simple example would be great.

    Thanks

    quovadis13 on
  • JaninJanin Registered User regular
    edited October 2008
    You could loop around calls to stat(), calling either sleep() or usleep() depending on how much time is required to create the files.

    Janin on
    [SIGPIC][/SIGPIC]
  • templewulftemplewulf The Team Chump USARegistered User regular
    edited October 2008
    Janin wrote: »
    You could loop around calls to stat(), calling either sleep() or usleep() depending on how much time is required to create the files.

    Are you talking about istream::stat()? I haven't had much cause to use it before. What does it do?

    templewulf on
    Twitch.tv/FiercePunchStudios | PSN | Steam | Discord | SFV CFN: templewulf
  • Airking850Airking850 Ottawa, ONRegistered User regular
    edited October 2008
    On the music-while-programming subject, I traditionally listen to trance / techno but lately I've been listening to a lot of death metal, especially Amon Amarth. It's pretty easy to tune out death-growl vocals, but when I need to clear my head I can focus on a man yelling about viking battles and get totally pumped.

    Airking850 on
  • urahonkyurahonky Registered User regular
    edited October 2008
    Airking850 wrote: »
    On the music-while-programming subject, I traditionally listen to trance / techno but lately I've been listening to a lot of death metal, especially Amon Amarth. It's pretty easy to tune out death-growl vocals, but when I need to clear my head I can focus on a man yelling about viking battles and get totally pumped.

    That's a good point. I put on some Lounge music as well to keep me from freaking out (doesn't help 100% of the time).

    e: Super Mario Galaxy soundtrack works very well too.

    urahonky on
  • JaninJanin Registered User regular
    edited October 2008
    templewulf wrote: »
    Janin wrote: »
    You could loop around calls to stat(), calling either sleep() or usleep() depending on how much time is required to create the files.

    Are you talking about istream::stat()? I haven't had much cause to use it before. What does it do?

    No, I mean the stat() function. http://linux.die.net/man/2/stat

    Janin on
    [SIGPIC][/SIGPIC]
  • ASimPersonASimPerson Cold... and hard.Registered User regular
    edited October 2008
    urahonky wrote: »
    Out of curiosity: How many of you listen to music while you program? If you do, what type of music? I tend to put on either Techno or Ambient because of the lack of words. That way I'm not focusing on them.

    My girlfriend thought it was weird that I was listening to music while programming last night. She said she wouldn't be able to concentrate.

    I'll say only if I don't get ostracised for it. Please don't judge out loud.

    I uhh... listen to... mmm... music from decades past - Bonnie Tyler and Meat Loaf, say. Yeah there are lyrics, but I know the songs well enough that I end up ignoring them.

    Can you see paradise by the dashboard light, eecc? :P

    But, yeah, I pretty much listen to my normal playlist. Which is a weird combination of classic rock, Cake, Radiohead, and video game music. Especially now that I do programming here in the cube farm, so I need something to block out the ambient noise. I do have a confession, though.
    You know that song "Clubbed to Death" from the original Matrix movie? You know, the one that's playing when Neo first goes back to the Matrix and Morpheus lectures him about the rules of the world and the Lady in the Red Dress and stuff?

    Yeah. I was a programming competition back in high school oh in 2001 or 2002 probably (you know, back when the Matrix was cool) and someone put on the Matrix soundtrack. That song made us all feel like programming badasses. And it still works for me to this day.

    At any rate urahonky, I think a girlfriend would've been more a distraction than any music could be. ;)

    ASimPerson on
  • urahonkyurahonky Registered User regular
    edited October 2008
    Oh man, Clubbed to Death by Rob Dougan or something? Yeah that song is fantastic for programming. Feels like you're actually hacking. You should listen to Faithless - Drifting Away, I'm not even kidding I knocked out half my program in the 6 minutes that song was on. :P

    Also, the program was already a day late and I was far behind. Apart from putting her rack in my face, I was going to focus mainly on my program.

    urahonky on
  • templewulftemplewulf The Team Chump USARegistered User regular
    edited October 2008
    Janin wrote: »
    templewulf wrote: »
    Janin wrote: »
    You could loop around calls to stat(), calling either sleep() or usleep() depending on how much time is required to create the files.

    Are you talking about istream::stat()? I haven't had much cause to use it before. What does it do?

    No, I mean the stat() function. http://linux.die.net/man/2/stat

    Ohhhhhhhhhhh!!! Well, that explains why I was so confused. :lol:

    Thanks for the reference. *book-a-mark*

    templewulf on
    Twitch.tv/FiercePunchStudios | PSN | Steam | Discord | SFV CFN: templewulf
  • EtheaEthea Registered User regular
    edited October 2008
    I work in an 'open' concept cubicle farm, so I have music playing constantly at work, mainly it is a mix of the following:
    • CBC - Definitely Not The Opera
    • CBC Radio 3 Top 30
    • StackOverflow PodCast
    • Electronic Radio Station
    • Absolute Radio England
    • Private Music Collection

    Ethea on
  • jonxpjonxp [E] PC Security Registered User regular
    edited October 2008
    urahonky wrote: »
    Out of curiosity: How many of you listen to music while you program? If you do, what type of music? I tend to put on either Techno or Ambient because of the lack of words. That way I'm not focusing on them.

    My girlfriend thought it was weird that I was listening to music while programming last night. She said she wouldn't be able to concentrate.

    I listen to the same types for the same reason. It drowns out external influences while not distracting me or being annoying.

    jonxp on
    Every time you write parallel fifths, Bach kills a kitten.
    3DS Friend Code: 2707-1614-5576
    PAX Prime 2014 Buttoneering!
  • nialscorvanialscorva Registered User regular
    edited October 2008
    quovadis13 wrote: »
    Continuing on with my great programming escapades. I am trying a new approach now and I need help with it.


    I have a C++ program and I need it to interact with other text files on a Unix system. I am now going to have the program hold up and wait in the middle for the text files to actually be created/updated. I am asking for help in writing some code that will cause the program to wait until all the necessary files are created.

    I am thinking that the best way to do this is have the C++ code wait for a new text file to update. How do I write the code that will make the program wait until this file is updated and then proceed as planned? I have been looking up the wait() command, but I am still a little bit confused. Some links or at least a simple example would be great.

    Thanks

    I'm not sure of your exact requirements, but the "tail -f" method might work for you. The situation is that you have a file F that is being written to at the same time you are reading. Your reader will usually outrun the writer. What you do is
    while(true)
    {
       while(!eof)
       {
          //read some and process
       }
       // arbitrary go away and come back later when there might be some data
       sleep(1); 
       // reset the eof without moving the read pointer
       fseek(FILE,0,SEEK_END);
    }
    

    nialscorva on
  • NightslyrNightslyr Registered User regular
    edited October 2008
    Hooboy, I have several questions, so please bear with me.

    First, can anyone help me out with my previous post? You can find it here: http://forums.penny-arcade.com/showpost.php?p=7628161&postcount=2088

    And now, to my most current issue. I've written the skeleton for the method that will actually level up my game's player characters. In order to avoid some overhead in copying objects all around the place, I simply want to pass the player character object to the method by reference. The problem is that, according to the compiler and what I've read on MSDN, I need to perform some sort of assignment to the value passed in by reference. I thought that my code would fit the bill, as I'm using some simple math to upgrade a player character's stats, but the compiler is telling me that it doesn't count. The method in question is:
    public void levelUp(out PlayerCharacter pc)
        {
            pc.TotalHP += (pc.TotalHP / 10) * pc.Class.HPMultiplier;
            pc.TotalTP += (pc.TotalTP / 10) * pc.Class.TPMultiplier;
    
            if ((pc.Level % 3) == 0)
            {
                if (pc.Class.GetType().ToString() == @"Hacker")
                {
                    //get a copy of the proper attack
                }
                else if (pc.Class.GetType().ToString() == @"Shill")
                {
                    //get a copy of the proper attack
                }
                else if (pc.Class.GetType().ToString() == @"Soldier")
                {
                    //get a copy of the proper attack
                }
                else
                {
                    throw new Exception("Bad character class");
                }
    
                //add attack to the pc
            }
        }
    

    Should I just use pass-by-value to save myself some headaches? Because other than the modified HP and TP values, and whatever special attack the character may get, I don't need to assign anything else to that object. And, from a design standpoint, would pass-by-value be a better way to go anyway, so I'm not relying purely on the method's side effect to do all the work?

    Nightslyr on
    PSN/XBL/Nintendo/Origin/Steam: Nightslyr 3DS: 1607-1682-2948
    Switch: SW-3515-0057-3813 FF XIV: Q'vehn Tia
  • iTunesIsEviliTunesIsEvil Cornfield? Cornfield.Registered User regular
    edited October 2008
    Watch me make a big idiot of myself here, but in .NET I believe all class-based objects are already passed by reference, so you don't need to do the "out" thing unless you've got a very specific reason for it. I think built-in's and structs are passed by value by default, but everything else is by reference.

    iTunesIsEvil on
  • NightslyrNightslyr Registered User regular
    edited October 2008
    Watch me make a big idiot of myself here, but in .NET I believe all class-based objects are already passed by reference, so you don't need to do the "out" thing unless you've got a very specific reason for it. I think built-in's and structs are passed by value by default, but everything else is by reference.

    Aha, you're basically right! (see: http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx)

    Thanks! :)

    Nightslyr on
    PSN/XBL/Nintendo/Origin/Steam: Nightslyr 3DS: 1607-1682-2948
    Switch: SW-3515-0057-3813 FF XIV: Q'vehn Tia
  • nlawalkernlawalker Registered User regular
    edited October 2008
    Nightslyr wrote: »
    Aha, you're basically right! (see: http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx)

    Thanks! :)
    Ref and out also have a couple of interesting caveats, above and beyond simply forcing a pass-by-ref for value types:

    If you use ref, the variable must be initialized before you pass it to the method call.

    If you use out, the variable doesn't have to be initialized before you pass it to the method call, but the method must assign a value before it returns.

    Thus, ref is best if you just want to straight-up pass something by reference, no strings attached. Out is best if you essentially want multiple return values - it enforces that the method must assign something.

    nlawalker on
  • NightslyrNightslyr Registered User regular
    edited October 2008
    nlawalker wrote: »
    Nightslyr wrote: »
    Aha, you're basically right! (see: http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx)

    Thanks! :)
    Ref and out also have a couple of interesting caveats, above and beyond simply forcing a pass-by-ref for value types:

    If you use ref, the variable must be initialized before you pass it to the method call.

    If you use out, the variable doesn't have to be initialized before you pass it to the method call, but the method must assign a value before it returns.

    Thus, ref is best if you just want to straight-up pass something by reference, no strings attached. Out is best if you essentially want multiple return values - it enforces that the method must assign something.

    Yeah, I read about that with 'ref' before, which is why I decided to go with 'out'. Unfortunately, I didn't know about/see the assignment caveat.

    Given my current function's signature:
    public void levelUp(PlayerCharacter pc)
    

    Should I change the return type to PlayerCharacter as well? It compiles as-is, but I'm wondering if it'd be better form to clearly specify a return type, even though I don't really need one as pc is a reference type.

    Nightslyr on
    PSN/XBL/Nintendo/Origin/Steam: Nightslyr 3DS: 1607-1682-2948
    Switch: SW-3515-0057-3813 FF XIV: Q'vehn Tia
  • nlawalkernlawalker Registered User regular
    edited October 2008
    Nightslyr wrote: »
    nlawalker wrote: »
    Nightslyr wrote: »
    Aha, you're basically right! (see: http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx)

    Thanks! :)
    Ref and out also have a couple of interesting caveats, above and beyond simply forcing a pass-by-ref for value types:

    If you use ref, the variable must be initialized before you pass it to the method call.

    If you use out, the variable doesn't have to be initialized before you pass it to the method call, but the method must assign a value before it returns.

    Thus, ref is best if you just want to straight-up pass something by reference, no strings attached. Out is best if you essentially want multiple return values - it enforces that the method must assign something.

    Yeah, I read about that with 'ref' before, which is why I decided to go with 'out'. Unfortunately, I didn't know about/see the assignment caveat.

    Given my current function's signature:
    public void levelUp(PlayerCharacter pc)
    

    Should I change the return type to PlayerCharacter as well? It compiles as-is, but I'm wondering if it'd be better form to clearly specify a return type, even though I don't really need one as pc is a reference type.

    First, before I forget, read this: http://msdn.microsoft.com/en-us/library/0f66670z.aspx. The correct description of behavior in C# not that "objects are passed by reference by default." It is that "object references are passed by value by default". Check out the difference when you pass a reference type using the ref keyword and not using the ref keyword. Good to understand.

    In my opinion, the best "form" would be to make LevelUp a method of PlayerCharacter, or whatever PlayerCharacter inherits from (if there are other kinds of things that can level up too). It comes down to the concept of "side effects:" a method invisibly fiddling with things inside a reference type instance. Side effects are good to avoid, although sometimes it makes sense to have side effects if your architecture comes together that way.

    For example, you'll usually only see methods with a signature like "T MyMethod(T myObject)", where T is some type, if T is a value type. See all the static methods of the System.IO.Path class as an example: they take strings and return strings. Doing this doesn't make that much sense for a ref type since you don't need to return the object - you passed it by ref in the first place.

    Which brings us to the true problem with side effects - using a method to fiddle with values inside of a reference type instance without clearly stating that you do so. They're called side effects because they can sneak up on you and are often unintended by the person using the method call. This is actually one of the reasons that you have to type "ref" or "out" in both the method declaration and when you actually call the method - so it's very clear that you are in fact handing in something by reference when you call the method.

    Best practice here, in my opinion, is to make LevelUp a method of PlayerCharacter. You're messing with values inside of a particular PlayerCharacter instance - you might as well make the method a member of that class.

    EDIT: The best analogy is a television. Let's say you have a Television class. Where should the ChangeChannel method go? Look to real life for the answer - the knob itself is on the TV, and even if you were doing it with a remote, the remote has to communicate with the particular TV (instance) that you want to change the channel on! ChangeChannel should be an instance method of Television.

    nlawalker on
  • Woot427Woot427 Registered User regular
    edited October 2008
    Alright, I need to go from a XSD to a database schema in Microsoft SQL server, any ideas? I'm googling this and go through results, but I was wondering if anyone has had to do this before or knows of a tool (not necessarily free).

    Woot427 on
  • NightslyrNightslyr Registered User regular
    edited October 2008
    nlawalker wrote: »
    Nightslyr wrote: »
    nlawalker wrote: »
    Nightslyr wrote: »
    Aha, you're basically right! (see: http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx)

    Thanks! :)
    Ref and out also have a couple of interesting caveats, above and beyond simply forcing a pass-by-ref for value types:

    If you use ref, the variable must be initialized before you pass it to the method call.

    If you use out, the variable doesn't have to be initialized before you pass it to the method call, but the method must assign a value before it returns.

    Thus, ref is best if you just want to straight-up pass something by reference, no strings attached. Out is best if you essentially want multiple return values - it enforces that the method must assign something.

    Yeah, I read about that with 'ref' before, which is why I decided to go with 'out'. Unfortunately, I didn't know about/see the assignment caveat.

    Given my current function's signature:
    public void levelUp(PlayerCharacter pc)
    

    Should I change the return type to PlayerCharacter as well? It compiles as-is, but I'm wondering if it'd be better form to clearly specify a return type, even though I don't really need one as pc is a reference type.

    First, before I forget, read this: http://msdn.microsoft.com/en-us/library/0f66670z.aspx. The correct description of behavior in C# not that "objects are passed by reference by default." It is that "object references are passed by value by default". Check out the difference when you pass a reference type using the ref keyword and not using the ref keyword. Good to understand.

    In my opinion, the best "form" would be to make LevelUp a method of PlayerCharacter, or whatever PlayerCharacter inherits from (if there are other kinds of things that can level up too). It comes down to the concept of "side effects:" a method invisibly fiddling with things inside a reference type instance. Side effects are good to avoid, although sometimes it makes sense to have side effects if your architecture comes together that way.

    For example, you'll usually only see methods with a signature like "T MyMethod(T myObject)", where T is some type, if T is a value type. See all the static methods of the System.IO.Path class as an example: they take strings and return strings. Doing this doesn't make that much sense for a ref type since you don't need to return the object - you passed it by ref in the first place.

    Which brings us to the true problem with side effects - using a method to fiddle with values inside of a reference type instance without clearly stating that you do so. They're called side effects because they can sneak up on you and are often unintended by the person using the method call. This is actually one of the reasons that you have to type "ref" or "out" in both the method declaration and when you actually call the method - so it's very clear that you are in fact handing in something by reference when you call the method.

    Best practice here, in my opinion, is to make LevelUp a method of PlayerCharacter. You're messing with values inside of a particular PlayerCharacter instance - you might as well make the method a member of that class.

    EDIT: The best analogy is a television. Let's say you have a Television class. Where should the ChangeChannel method go? Look to real life for the answer - the knob itself is on the TV, and even if you were doing it with a remote, the remote has to communicate with the particular TV (instance) that you want to change the channel on! ChangeChannel should be an instance method of Television.

    Once again, thanks. I've switched some things around, and, like you say, it is more logical (and I daresay simpler) doing it this way. For the curious, who may be following along, I renamed my LevelFactory class to AttackRegistry, and things work like so:

    My levelUp method in my PlayerCharacter class:
    public void levelUp()
        {
            this.totalHitPoints += (this.totalHitPoints / 10) * this.charClass.HPMultiplier;
            this.totalTechPoints += (this.totalTechPoints / 10) * this.charClass.TPMultiplier;
    
            if ((this.currentLevel % 3) == 0)
            {
                AttackRegistry attackReg = new AttackRegistry();
                Attack newAttack = attackReg.getAttack(this);
                this.attacks.Add(newAttack);
            }
        }
    

    Here, this.attacks is a simple List<Attack>, so Add just adds the newAttack to the end of the list.

    And my getAttack method in my AttackRegistry class:
    public Attack getAttack(PlayerCharacter pc)
        {
            if (pc.Class.GetType().ToString() == @"Hacker")
            {
                return hackerAttacks.Retrieve(pc.Level);
            }
            else if (pc.Class.GetType().ToString() == @"Shill")
            {
                return shillAttacks.Retrieve(pc.Level);
            }
            else if (pc.Class.GetType().ToString() == @"Soldier")
            {
                return soldierAttacks.Retrieve(pc.Level);
            }
            else
            {
                throw new Exception("Bad character class");
            }
        }
    

    Here, hackerAttacks, shillAttacks, and soldierAttacks are all objects deriving from a base Attacks class, which, in turn, is derived from the built-in Dictionary class. So, Retrieve returns the appropriate special attack based on the character's level.

    Nightslyr on
    PSN/XBL/Nintendo/Origin/Steam: Nightslyr 3DS: 1607-1682-2948
    Switch: SW-3515-0057-3813 FF XIV: Q'vehn Tia
  • SliverSliver Registered User regular
    edited November 2008
    I know how much programmers like vague and nebulous questions like this but I'm going to ask it anyways so bear with me.

    Quake 3 is open source and I want to eventually work up to the point where I can tinker with the engine, or another one like it.

    Exactly what am I going to need to know so I can open it up and know what the hell it is I'm looking at?

    Sliver on
  • EtheaEthea Registered User regular
    edited November 2008
    Sliver wrote: »
    I know how much programmers like vague and nebulous questions like this but I'm going to ask it anyways so bear with me.

    Quake 3 is open source and I want to eventually work up to the point where I can tinker with the engine, or another one like it.

    Exactly what am I going to need to know so I can open it up and know what the hell it is I'm looking at?

    At least:

    C/C++, OpenGL, and linear algebra.

    Fake Edit:
    This better turn you on: http://www.codemaestro.com/reviews/9

    Ethea on
  • SliverSliver Registered User regular
    edited November 2008
    Will I need to know any more advanced math like geometry or trig?

    Sliver on
  • ecco the dolphinecco the dolphin Registered User regular
    edited November 2008
    Sliver wrote: »
    Will I need to know any more advanced math like geometry or trig?

    Yup.

    If you want to rotate anything in 3D space, or understand how something is being rotated in 3D space, you need to at least be familiar with basic trignometry.

    Edit: I imagine if you'd gain a lot out of looking at the Quake 3 engine if you had a bit of programming experience under your belt. That way, you could ask questions like, "So... why did they organise data that way?" and hopefully be able to tinker a bit and realise, "Oooh, so that access times are minimised/constant/whatever."

    ecco the dolphin on
    Penny Arcade Developers at PADev.net.
  • EtheaEthea Registered User regular
    edited November 2008
    Sliver wrote: »
    Will I need to know any more advanced math like geometry or trig?


    It sounds like you don't program much, if that is a case you really need to start with the fundamentals in math. So you need Trig/Geometry/Linear Algebra/Finite/Graph theory.

    Ethea on
  • SliverSliver Registered User regular
    edited November 2008
    Fiddlesticks. I was worried you'd say something like that.

    Are there any good books or websites you'd recommend that are specifically on the subject of programming and 3D math?

    EDIT: I took a class in VB a few years ago, hated it, and forgot most of what I'd learned. I know about programming, but not how to. If that makes any sense.

    Sliver on
This discussion has been closed.