Archived

This topic is now archived and is closed to further replies.

xorjesus

What is the best way to Convert a char to a char *

Recommended Posts

xorjesus    100
What''s the best way in GAME PROGRAMMING(i.e. fastest) way to convert a char to a char *. I need to do this so I can use string.insert() with a functiont that returns a char. Thank you for any replies.

Share this post


Link to post
Share on other sites
RuneLancer    253
A function asking for a char* wants a zero-terminated string. For instance...

''H'', ''e'', ''l'', ''l'', ''o'', 0

That''s a char[6] containing "Hello"

A char* is a pointer to the first element of this string. So you''d pass &YourChar[0]. However, since an array is already a pointer, you can just pass YourChar.

If you meant a regular char as opposed to an array of chars, then you can''t. You''ll have to make it at least an array with two elements, since these functions expect to have a 0 to tell them when to stop reading stuff from memory.

Share this post


Link to post
Share on other sites
SoulSpectre    169
You need to be a bit more clear as to what you want here. Do you want a pointer to a char or a null terminated string? If it is to a null terminated string then simply create an array:

char c[2].
c[0] = somefuncthatreturnachar();
c[1] = 0;
string.insert(c);

If this isn't what you wanted you need to explain the situation a bit more.

EDIT: typo

[edited by - SoulSpectre on May 26, 2004 2:50:19 PM]

Share this post


Link to post
Share on other sites
RuneLancer    253
Why do you need this to be fast, anyways? You''re stressing the fact it has to be the fastest way to do it, but really, this is a trivial operation. Optimizing the way your game appends strings to each other is the least of your worries. This is what we call microoptimization.

Of course, it depends what you use it for, but I can''t really think of a reason why it would be such a performance issue. So don''t worry about it.

Share this post


Link to post
Share on other sites
Agony    3452
2 easy ways:

std::string.insert() can take two parameters (beyond the first parameter of insert location), a number, and a char. The number represents how many of that char to insert.

std::string.insert() can also take two parameters (again, beyond the first one), a char* and a number. The number specifies how many characters to copy, and doesn''t need a null-terminated string.
std::string s;
s = "blah";
char AChar;
AChar = FunctionReturnsChar();
s.insert(2, 1, AChar); // s == "bl?ah"

s = "blah";
AChar = FunctionReturnsChar();
s.insert(2, &AChar, 1); // s == "bl?ah"

s = "blah";
s.insert(2, 1, FunctionReturnsChar(); // s == "bl?ah"

Share this post


Link to post
Share on other sites
xorjesus    100
quote:

If you meant a regular char as opposed to an array of chars, then you can''t. You''ll have to make it at least an array with two elements, since these functions expect to have a 0 to tell them when to stop reading stuff from memory.


Yes I meant just a char, not an array of char.

quote:

You need to be a bit more clear as to what you want here. Do you want a pointer to a char or a null terminated string? If it is to a null terminated string then simply create an array


Yes I meant to a null terminated string.

quote:

Why do you need this to be fast, anyways? You''re stressing the fact it has to be the fastest way to do it, but really, this is a trivial operation. Optimizing the way your game appends strings to each other is the least of your worries. This is what we call microoptimization.

Of course, it depends what you use it for, but I can''t really think of a reason why it would be such a performance issue. So don''t worry about it.


I respectfully, disagree with you Rune Caster. We can have a good argument/discussion about this, If argument/discussions are as stimulating to you as they are to me. I agree with you that microoptimazation is a lower priority in a game when compared to higher levels of optimzation. I disagree with you when you tell me not to worry about it. My philosphy about speed is this. I feel throughout the development process, if enough microoptimaztions are applied to the game, it can possibly equate to half the gain of a large optimzation, or maybe even more. The amount of ms(micro second) speed gain is proportional to the amount of microoptimazations applied. The magnitude of speed gain is significantly scaled propotionaly based on the hardware your developing for, and the running time of your program. A few ms could be nill in a single player shooter that is hosted on a p4 3 gig uber comp. But on a tool that that runs week long tests on the physics of stars colliding, or a game boy advance trying render mario 3d, I believe those speed gains are very important. I''m also just a guy interested into doing things in a speedy way :] If I unify these microoptimazation concepts into the foundation of my programming, I''ll be cranking out uber effiecent code that will be viable on many more systems, instead of just the newest uber super computer.

Share this post


Link to post
Share on other sites
bytecoder    100
quote:

I respectfully, disagree with you Rune Caster. We can have a good argument/discussion about this, If argument/discussions are as stimulating to you as they are to me. I agree with you that microoptimazation is a lower priority in a game when compared to higher levels of optimzation. I disagree with you when you tell me not to worry about it. My philosphy about speed is this. I feel throughout the development process, if enough microoptimaztions are applied to the game, it can possibly equate to half the gain of a large optimzation, or maybe even more. The amount of ms(micro second) speed gain is proportional to the amount of microoptimazations applied. The magnitude of speed gain is significantly scaled propotionaly based on the hardware your developing for, and the running time of your program. A few ms could be nill in a single player shooter that is hosted on a p4 3 gig uber comp. But on a tool that that runs week long tests on the physics of stars colliding, or a game boy advance trying render mario 3d, I believe those speed gains are very important. I''m also just a guy interested into doing things in a speedy way :] If I unify these microoptimazation concepts into the foundation of my programming, I''ll be cranking out uber effiecent code that will be viable on many more systems, instead of just the newest uber super computer.


Micro optimisations are just that, micro. However, the same operation may or may not be considered a micro optimisation depending on where it is within the code. For example, a simple char -> string operation by itself is a micro optimization, but if you had that same optimization in a tight loop then you''d probably want to optimise it. The reason you shouldn''t bother optimising it if it doesn''t matter, because you''ll end up spending a bunch of time on something that gives you absolutely no gains.

Share this post


Link to post
Share on other sites
xorjesus    100
Well every (main loop) iteration, the conversion will take place serveral times. It's not like it's happening just once. But that brings me to one of the points in my argument. If you have many different operations that only have happen once in a while, and they're all optimized to begin with. I would consider that a worthy speed gain, overall. In learning the process of game programming, I see no problem in taking the time to learn to subconciously/automatically write your code with micro optimizations applied.

[edited by - xorjesus on May 26, 2004 8:40:42 PM]

Share this post


Link to post
Share on other sites
Zipster    2365
In practice, productivity is also an issue. When you''re programming at home as a hobby, you really have all the time in the world to experiment with optimizations, trying to write the fastest rasterizer or square root function, etc. But in a professional environment, there are deadlines that have to be met, and not a lot of time to tinker with how fast you can optimize everything you write. Only code that is run most often should receive the benefit of an intense optimization stage.

You have to weigh the benefits of a slightly faster optimization with how long it takes to implement. If there''s an obviously faster way to do something than the current way you''re doing it, then you should go ahead and do that (like doing i = j rather than i = sqrt(j)*sqrt(j)). But if you spend too much time optimizing something that doesn''t give you any notable speed games overall, then you really shouldn''t worry about it. Sometimes, too many micro-optimizations can actually hurt performance, as you could inadvertently inhibit the compiler''s ability to detect places where it can make its own optimizations. And more recent compilers do a very good job at optimizing.

In this specific instance, converting a single character to a null-terminated string can only be broken down into a small series of atomic operations, so there shouldn''t be too much dispute over which is fastest. I''d second what SoulSpectre suggests. You really can''t make it much faster.

Share this post


Link to post
Share on other sites
Agony    3452
Well, I can''t tell if my suggestions totally got missed, but if they did, I''ll just point out again that you do not need to convert anything to a null-terminated string when using std::string::insert(). I illustrated two ways to do it that are in most likelihood just as fast or faster than adding a ''\0'' onto the end of a 2-byte array or anything else I can think of.

Of course, at the same time, insert() isn''t really all that fast of a function anyway, since you''re going to have to copy on average half of the characters of the string into which you''re inserting a char. Finding a better way of getting all the characters where you want them, if possible, would be much more effective, at least in this specific case. Or maybe finding a way to be able to simply use append() instead of insert().

(Note that I mostly agree with you xorjesus, in reference to learning how to automatically/subconsciously apply micro-optimizations. Specific to this example, though, a macro-optimization, if possible, would be significantly more noticeable.)

Share this post


Link to post
Share on other sites
xorjesus    100
Agony, your suggestion was not missed, as a matter of fact I''m using the overloaded version of insert you suggested. I didn''t fully understand how it worked before. I assumed insert(how many copies I want, char) was actually insert(index posisition, char). That''s why when I was testing insert(0, char) and it worked, I got stumped when I tested insert(n, char) where n > 0. Your right about the macro optimization in finding a solution to my problem, one where I do not use std::strings. Though the reason I turned to strings in the first place was an easy and elequent way to deal with memory leaks. You see my functions return c-strings before I had a chance to delete the memory. In my list of solutions, I wanted to gain some experience working with strings, so I went to work rebuilding my functions with strings in the place of my original dynamically allocated c-strings.

Share this post


Link to post
Share on other sites
kdogg    204
not to stride too far from the question, but since the OP led us down this path, you'll find that micro optimisations usually makes no noticable difference. After you're done with your program and run it through an optimiser (or whatever technique you like to use) you'll find that 90% of your code is probably spent in the same 2 or 3 functions. So, you end up spending hours getting a 1% gain in performance at an area your program spends .5% of it's runtime in for an overall gain of .005%. And that's if you're lucky. In the meantime, you've butchered the readability of your program and you're not gonna be able to easily expand it or take care of unforeseen circumstances. In the end, your micro optimisations have ended up preventing a program from even being completed.

And so, the conclusion, is that readablility and algorithm design are the most important aspects of programming. All the optimisation in the world won't overcome a bad algorithm, and all the speed in the world won't overcome a cryptic program when it comes time to expand or debug. Too many things can go wrong and there's too little to gain. It seems like the fastest and most readable solution to your problem would be to find a way to avoid this conversion all together. Read your character into th 0th position of a length 2 array. Then you've got a char* in the array and, if you ever need the character, just use the subscript. Then you'll have eliminated the need for a conversion all together and it will be obvious what the code is doing.

[edited by - kdogg on May 26, 2004 10:41:24 PM]

Share this post


Link to post
Share on other sites
RuneLancer    253
quote:
Original post by xorjesus
I respectfully, disagree with you Rune Caster.


RuneCaster? Who the fuck is that?

I used to share your philosophy. Then I realized I was wrong, plain and simple.

The only place where microoptimizations are worthwhile is in a very, very tight loop. If you have a full-screen per-pixel graphic effect, even at 800x600 it would be called 480,000 times per frame. Something that takes 0.0001 millisecond would make a rather huge difference here (48 ms; which means a max of 20 FPS even if there's no additional overhead at all from anything else) In such a situation, yes, it's worth it.

However, outside of tight loops, you're just wasting your time. You could have an algorithm that's allright, and micro-optimize it to perfection. Then you might end up seeing a less than 0.1 FPS increase if it's moderately important to your game. OR, you can replace it with a better algorithm, and gain a few extra FPS.

You might figure, well, why not micro-optimize every function like this and end up gaining maybe 1-2 FPS from unimportant, time-consuming decisions on wether your loop that fills an array with numbers from 1 to 100 should be done via (i=0;i<100;i++) or (i=100;i--;; ). Why not just replace them all by better algorithms and gain a couple dozen FPS more, then?

Finally, there's readability issues. Using the two for loop examples I've provided up there, which seems easier to read? Unless you've been doing the latter frequently, the first would be more intuitive: you're counting from 0 to 100 exclusively. The latter, personally, makes me intuitively feel as though someone forgot to put an escape condition in their for loop and messed up with their semi-colons, at first glance.

I doubt any post here will change your mind. Just know that unless you're working in a tight loop, you're wasting your time and won't see any difference, and will eventually decide to spend time on more "macro" optimizations. Try this... write a game. Don't micro-optimize. Now make a copy and micro-optimize. Make sure they're only micro-optimizations, no other form of optimization is allowed. Compare.

Good luck on your projects!

Edit: STOP. CHANGING. MY. DAMN. ; ). TO. A. . YOU. STUPID. BOARD!! :x Gah! -_-

[edited by - RuneLancer on May 26, 2004 11:08:58 PM]

Share this post


Link to post
Share on other sites
xorjesus    100
quote:

I doubt any post here will change your mind.


On the contrary, I''m a very open minded person, I''ve found this has helped my success in the real world quite a bit.(school, job, hobbies, social interactions) I''ve learned quite a bit from this thread alone, and it''s reinforced some ideas I''ve had, but I doubted the ideas within myself. I needed some good arguments/opinions/facts. I have a better idea of what true productivity is; based on possible bonuses/loses vs time spent implementing code. I''ve a clear difference of micro optimazation vs macro optimization thanks to most of the respondents, espcially kdogg and you. I now realize where my optimization time should be spent, and the importance of readability(makes lots of sense). I will continue to make my general code effiecient, but if it''s not part of the code that gets called 90% of the time, or I completely obliviate any form of readability, i''ll take a step back and think about what I''m doing. Thanks for all replies. You all stated your arguments and suggestions extremely clearly. I really do appreciate the help. GL to you all.
-xorjesus

Share this post


Link to post
Share on other sites
RuneLancer    253
Of course, it pays to know the fastest way to do stuff and to try to do it as a habit, but the compiler often does that on its own. I myself pretty much always write bitshifts instead of multiplications and divisions, even though it''s less readable and the compiler does it when it can anyways. Still, it can pay to try to find the fastest way to do even simple things, just so long as that knowledge is put to use right.

While pretty much everyone have argued microoptimization is not a very worthwhile thing to do, you should still clean up here and there. But only after you''re done with everything else. The "polishing off" phase of programming is a little different from the "making it work" phase, during which you should focus your efforts on the more important things.

Good luck with your project; may the coffee be with you!

Share this post


Link to post
Share on other sites