Thread: Hello, bored reading and a bunch of questions.

  1. #1
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85

    Hello, bored reading and a bunch of questions.

    Hello to all.

    First post, that's right, so it's time for a short presentation. (When I say short I really mean a long one, I do that allot).

    I'm 14, from Portugal and started programming C++ about one and a half year ago. Before that, I was stuck with HTML, CSS and basic JavaScript programming, so I decided it was finally time to move onto something more 'non-web-related'. I would never be able to have classes. First because I've never really learn't anything about anything that isn't tutored at school outside of it.

    I decided to google for something and I found this site which I must say that, although it is not perfect, it sure taught me allot! So thanks to all of Regular Forum users and tutorial writers and all those people in charge of this domain!

    Now, some info on what i've done 'till here.

    Back a year ago when I was still reading tutorials I had this 'great idea' of the 'prefect game'. I decided I would work on it and so I did, I started off with my 'archaic-like' programming and made a quite nice engine that outputted to console. No wait, scratch that, what I really meant was that: 'I made a really crappy engine that caused lot's of errors and got me tired of programming until I gave it up'. yes, looking back I think that's the correct description.

    Time passed and I never touched Dev-CPP again (back in the time when I thought Dev-CPP was a compiler and I thought that what they did was magic to turn code into executables) until the day a friend of mine asked me how 'the Game' was. Then I decided I would make a GUI, replacing all the old 'colourful console codes' with API one's. I evolved throughb phases, programmed one week, didn't program the next one and so on.

    I got lot's of nice functions for everything since registry manipulation to Window painting functions and C-like Strings functions. (Yes, although I consider myself a C++ programmer I rarely use String, Is tick with pure ol' char *||[].

    I got tired again after all, I have a life, a school life...gave up the project, the Engine was way to buggy. I decided to port lot's of code and make another game, a project 'Company Tycoon'...well, it's dumped now, at least suspended.

    We're getting closer to present day, at the moment we're taking of December 2007 when I was focused on learning deeper concepts of programming, I started involving projects like OpenTTD and ReactOS and decided to dump my 'old programming style'. Well, I didn't Ğdecideğ, it just happened. I dumped my 'all code in headers', 'slower is better' and 'hey, who needs Linked Lists? Arrays do the job!' pathetic theories...

    I started learning WSocket programming and made a chat application. Simple and in the console. Multiple clients connect to server.

    Let's just say I got a moving project, haven't stopped programming since then and have a Chat Application working with a good GUI that allows to chat, multiple commands like name changing, name memorizing, list commands and lots of future features I have already planned to code (and thought of how to code them). But most important, I implemented a way to send files (OK, it isn't that amazing, but let's think I'm 14, i've been working alone without posting code anywhere and I managed to get all my friends to use this because it sends files up to 2000% (in extreme situations) faster than Skype or MSN and because they simply like the idea of using and testing some made by someone they know).

    BTW, at the moment I'm working on things like Admins, I mean User Privileges, I call it Client Privilege Protocol.
    Well, that was it, I don't know if you read it but if you did you've got a hell of a patience! I myself wouldn't be able to read something about a 14 yrld portuguese kid.

    Now to my questions, I believe they are really basic and probably many won't answer them but here they come.

    JUMP HERE IF YOU DON'T CARE ABOUT MY PRESENTATION

    1. Which one do you think is better? (I know, regular question, just want your opinion)
      Code:
      void SomeFunction(SomeType x) {
      if(x) {
      //Some Code...
      }
      else {
      return; //Error. Escape
      }
      }
      Code:
      void SomeFunction(SomeType x) {
      if(!x) return; //Error. Escape
      
      //Some Code...
      }
      Code:
      void SomeFunction(SomeType x) {
      //Go One through code
      Function1();
      Function2();
      //Now we need to use x
      if (!x) return; //Error. Escape
      }
    2. Do you agree with loops like:
      Code:
      bool bExit=false; while(!bExit) { //work
      bExit=true; //Exit the loop}
      or do you think the best choice is:
      Code:
      while(true) { //work
      break;//Exit the loop}
    3. Ok, this is gonna get complex. Let's imagine function 1:
      Code:
      int g_aValue;
      void Function1(void) {
      while (true) {
      FunctionX();//Do Some work
      FunctionY(); //Some more Work
      g_aValue=FunctionZ(); //Affect g_aValue
      if(GottaExitCauseWorkIsDone()) break;
      }
      }
      Now let's imagine that is a long loop and that we need to use g_aValue elsewhere in parallel using threads let's say to print text so we'd have that:
      Code:
      int g_aValue;
      void Function1(void) {
      FunctionX();//Do Some work
      FunctionY(); //Some more Work
      g_aValue=FunctionZ(); //Affect g_aValue
      }
      
      void Function2(void) {
      cout<<g_aValue; //Access g_aValue and print it
      }
      Would Function2 slow down Function1 by accessing its memory address? If yes, what would you recommend to me to keep Function1 the faster as possible?
    4. What do you think is the fastest way to compare to strings (I mean C Strings) so that they are exactly equal? (I have my own code, wanna check yours if you may)
    5. For WSockets programmer's. Imagine I have a function that sends a piece of data through a socket and that immediately after that sends another piece of data. What has happened to me was that these two pieces of data merged in the same (I think it's because one Send does not Equal to one Recv)
    6. Do you agree with dynamic arrays (I mean arrays that are defined according to the value of another array or size)?
    7. I have experienced some problems with what I call 'memory saving'. Memory Saving and Time Saving are everything to me, so I did a risky business which put me a great ammount of bugs in the Chat (and I figured out that my 'perfect game' had these problems) so, here comes the code. I had this code in my Chat Application (cutting down other variables and leaving the essentials):
      Code:
      struct Client
        {
          char *Name;
          char *CurrQueueAct;
          Client::Client();
        };
      Client::Client()
      {
        Name = new char;
        CurrQueueAct= new char;
      }
      Well, I thought it seemed ok and it didn't have a defined size so it would be great! WRONG, I don't know what I did but I got to a point where CurrQueueAct would overlap Name and this happened with other variables too. My point is: Is this wrong? if it is, what is it?


    Well, I am really sory for boring you so much, so I'll leave my other questions for later. I just wanted to say that I have my theories for all these questions but want to know if I am right.

    Thank you.

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    These are good questions for someone your age.

    For the first few questions, the answer is highly opinionated. The early breaks and early returns can be viewed as breaking from the concept of structured programming. On the other hand, not using them can lead to deep nesting and code duplication which makes code harder to read and maintain. If you feel comfortable with early returns/breaks/continues, then use them. If you find yourself working for someone else (hopefully not for a while yet!) and they don't like it, then don't do it. Matter of style, basically.

    Would Function2 slow down Function1 by accessing its memory address? If yes, what would you recommend to me to keep Function1 the faster as possible?
    Possibly. The access by another thread could theoretically trigger some cache behavior that slows down access to that variable. But that is so highly system dependent I would not worry about it. More important is making sure your multithreaded access is properly synchronized. And that synchronization will add enough overhead that the memory effects are no longer important.

    What do you think is the fastest way to compare to strings (I mean C Strings) so that they are exactly equal? (I have my own code, wanna check yours if you may)
    strcmp(). It is tuned for the exact architecture, and probably does things which you can't possibly do in C code.

    For WSockets programmer's. Imagine I have a function that sends a piece of data through a socket and that immediately after that sends another piece of data. What has happened to me was that these two pieces of data merged in the same (I think it's because one Send does not Equal to one Recv)
    Exactly correct. There is no guarantee that a single send() will match with a single recv().

    Do you agree with dynamic arrays (I mean arrays that are defined according to the value of another array or size)?
    It's impossible to "disagree" with them -- they are critical to writing programs that do "real things."

    Well, I thought it seemed ok and it didn't have a defined size so it would be great! WRONG, I don't know what I did but I got to a point where CurrQueueAct would overlap Name and this happened with other variables too. My point is: Is this wrong? if it is, what is it?
    What is wrong is you are only allocating single characters for those variables...

    Good questions.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    1. I prefer the second over the first. The third does something different, so I'm not sure how it applies. I still use that version when necessary.
    2. I don't really care. I probably use the second version more.
    3. I don't think it would slow down, and I wouldn't worry about premature optimization.
    4. I wouldn't really care in my programming. I would use strcmp in C.
    5. What's your question?
    6. This isn't a proper question. Are you asking if we agree that they are ok to use? If so, then yes, there are many uses for dynamic arrays, although I have yet to hear a good argument for using a plain dynamic array in C++. You should use vector instead.
    7. You are allocating a single character. So if your Name is 'P' then it is fine. But that's not what you want. You have to allocate a size, and if your name is bigger then allocate again and copy over to the new memory location (and clean up the original). This is why people use C++ strings. You don't have to specify a size, it just works.

  4. #4
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    Thanks for the fast answers.

    Well, first I got that I didn't really make a question in 5. Sorry for that, but what I meant to ask was if I was correct.

    This isn't a proper question. Are you asking if we agree that they are ok to use? If so, then yes, there are many uses for dynamic arrays, although I have yet to hear a good argument for using a plain dynamic array in C++. You should use vector instead.
    Yes, that's what I was asking and thankyou for the answer.

    In terms of question 7 well, when I first saw the code I thought that was it and that's why I finally got a fixed size so, I was right after all. What I think is weird is that even though I only allocated a char, the text I got into it was actually being all 'caught'. The string manipulation functions probably, as it is a pointer, followed the sequence until the null-terminator. I guess that's it, or am I wrong?

    strcmp(). It is tuned for the exact architecture, and probably does things which you can't possibly do in C code.
    Well, first, thanks, secondly, that was what I used some time ago but I can't know why it actually didn't work. It ended up by only comparing if there was a string inside that string that was equal in both...oh well, now that i think about it, it was quite a long time ago and i probably used strstr() as I was quite lost in standard functions. Oh well, time to replace my IsStringEqual() and IsStringBegginingEqual() content with the correct content using strcmp(). thanks.

    It's impossible to "disagree" with them -- they are critical to writing programs that do "real things."
    That really got me thinking: 'Hey, it's definitely right!'
    I just had this question because back when I used VC++2005 I tried using dynamic arrays and it would not allow me, but GCC did, so I guess I had that doubt.

    You have to allocate a size, and if your name is bigger then allocate again and copy over to the new memory location (and clean up the original)
    I had never really thought about strings that way for a long time...that shows how much i have to learn. the last time I thought about them like that was when I was learning...now that just made my day, I think I'm definitely using C++ strings now...the transition will take a while but I will make it

    Thanks again.

  5. #5
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Jorl17 View Post
    That really got me thinking: 'Hey, it's definitely right!'
    I just had this question because back when I used VC++2005 I tried using dynamic arrays and it would not allow me, but GCC did, so I guess I had that doubt.
    Well, don't get confused. What I mean by a dynamic array is something allocated with malloc(). You can't in general, do this:

    Code:
    int array_size = something;
    int my_array[array_size];
    It works on GCC, but it's not standard and you shouldn't do it. The idea of an array whose size is based on some variable, instead of a constant, is valid though.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Just a quick one before I go through and properly answer all your questions:
    http://cpwiki.sf.net/Buffer_overrun
    That's what you get for using C-style strings.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    I just had this question because back when I used VC++2005 I tried using dynamic arrays and it would not allow me, but GCC did, so I guess I had that doubt.
    Are you talking about
    Code:
    void foo(int n)
    {
      int ar[n];
    }
    ?

    Those are not essential. They're not part of C++, only of C99. GCC supports them as an extension in C++.
    In C++, just use std::vector.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    It works on GCC, but it's not standard and you shouldn't do it. The idea of an array whose size is based on some variable, instead of a constant, is valid though.
    Quote Originally Posted by CornedBee View Post
    Are you talking about
    Code:
    void foo(int n)
    {
      int ar[n];
    }
    ?

    Those are not essential. They're not part of C++, only of C99. GCC supports them as an extension in C++.
    In C++, just use std::vector.
    To both of you, yes, I was thinking about that so I'll guess i'll start using vectors then. Thanks.

    Just a quick one before I go through and properly answer all your questions:
    http://cpwiki.sf.net/Buffer_overrun
    That's what you get for using C-style strings.
    Nice article, I actualy didn't know about that 'wiki', I'm gonna peak in there. Thanks.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    1) Second one. Typically it means less indentation levels, instead of if (succeeded) if (succeeded), etc. If it fails, just clean up and return. It's better in the long run too since it makes it easier to read the code than a huge level of ifs and elses.
    And the third one might not be the best, seeing as you might want to check for error after each.

    2) I like the break alternative. But if possible, it's better to place the conditions inside the loop header. Allows the compiler to do optimizations better, I'm told.

    For 3) I don't think either approach is bad. You just need a synchronization object somewhere there and it's probably going to take just as much time either way if you do that.

    4) Strcmp. Remember that it returns 0 if the strings are equal, not true or > 0.

    6) What's that question?

    And as for 7, most likely you're trigger buffer overrun, which is exactly what the article I linked to explains about.

    And btw, in C++, we use new/delete, not malloc/free.
    And I do suggest you start using std::string or your own homebrew string class. No buffer overrun errors there if you use it properly.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Mar 2008
    Location
    Coimbra, Portugal
    Posts
    85
    6) What's that question?
    Want I meant was if it was safe and OK to use them...acording to the answers I got, I see not

    And btw, in C++, we use new/delete, not malloc/free.
    Thanks but, for now I don't get mistaken with that I was never a C programmer so I learned new/delete before I learned malloc/free (and their Win32 API correspondents)

    Well, thanks to all for answering my questions.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Jorl17 View Post
    Want I meant was if it was safe and OK to use them...acording to the answers I got, I see not
    It is OK to do it, but you should avoid it when possible because it can result in memory leaks.
    There are safe pointers out there too, that can take care of that bit.
    But arrays are best as std::vector, because it guarantees (if you use it right) no buffer overruns.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> The string manipulation functions probably, as it is a pointer, followed the sequence until the null-terminator.

    Yes, that sounds like exactly what was happening.

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    1-3 barely matters if you fix the indentation.

    4. See http://www.nist.gov/dads/HTML/stringMatching.html

    5. Correct, fragmentation and reassembly is your problem to solve over a TCP connection (which is a stream protocol). UDP is packet based (1 send = 1 recv), but is unreliable into the bargain.

    6. "Do you agree with dynamic arrays", no, they give me indigestion
    What sort of question is that? Sooner or later you'll need data structures who's size can only be determined at run-time.

    7. "My point is: Is this wrong? if it is, what is it?"
    It's your responsibility to keep track of the size of the allocation as well, and ensure that you don't access pass the end of the assigned space. If you don't want to do that, use a std::string.

    > so I did a risky business which put me a great ammount of bugs in the Chat
    You need to make it "right" before you even consider making it smaller, faster, whatever.
    It's called "premature optimisation disease".
    If you're using C++, then use every creature comfort offered by STL and/or boost to make your day to day life easier. A program 5 seconds quicker, but delivered 3 months late won't buy you any praise.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  14. #14
    Registered User
    Join Date
    Apr 2007
    Posts
    141
    I found your story amusing but I only want to comment about one thing, being a C++ newbie myself. The fastest way to compare a lot of strings is to do something called string interning.

    You enforce a unique copy of a string in a container or map of some type and associate a unique integer to the string. That integer could be really just the pointer to the character array, but maintaining uniqueness is important. Then comparing string equality becomes comparing the integers/pointers

    Code:
    if (strint1 == strint2) {
    .....
    }
    The utility of this all depends on how much manipulation you perform on your strings and whether you support substrings pointing to the same location in memory etc. In general you have to treat your strings that are interned as immutable (unchangeable).

    Also it's really only useful if you reuse the same strings a lot. That's because every time you create a new immutable string you have to check to see if it's already in your map or string hash table, depending on how you implement it. My guess is if you are parsing tokens from a limited vocabulary, this technique is ideal.

Popular pages Recent additions subscribe to a feed