• What Do You Need Help With? V6
    7,544 replies, posted
Is it better to use [code] Console.WriteLine("Value of {0} is {1}", object, value); [/code] rather than [code] Console.WriteLine("Value of " + object + " is " + value); [/code] ?
[QUOTE=Funley;43312886]Is it better to use [code] Console.WriteLine("Value of {0} is {1}", object, value); [/code] rather than [code] Console.WriteLine("Value of " + object + " is " + value); [/code] ?[/QUOTE] Not necessarily, and probably not how you think. The compiler turns the latter into [code]Console.WriteLine(string.Concat(...,...,...,...));[/code], but the console formatting may still be faster by not allocating the result as string. [I]string.Concat[/I] has overloads for up to four parameters, so you avoid creating an array either way. Whether scanning for replacement codes or trying to intern the result string is faster is a question for benchmarks, but I'm leaning towards saying the concatenation with string result wins by a small margin in this case. It's possible that number formatting avoids the intermediary string though, in which case the formatting may be faster. [editline]26th December 2013[/editline] Regarding i18 the format string wins hands down though.
[QUOTE=Rayjingstorm;43284772]If you write exclusively in modern C++ (or any object-oriented language) why would you wish to put up with the C methodology of free-functions and structs? Those techniques may be the standard for a purely procedural language, but object-oriented compilers provide facilities for abstraction which SDL doesn't exploit while SFML does.[/QUOTE] Wait what? Are you complaining that a c library is not written in c++? If you want it to match your language then write a wrapper. Most people would consider it an advantage for a library like SDL to be c.
[QUOTE=Philly c;43315120]Wait what? Are you complaining that a c library is not written in c++? If you want it to match your language then write a wrapper. Most people would consider it an advantage for a library like SDL to be c.[/QUOTE] [i]Most people would consider it an advantage for a library like SDL to be c.[/i] You miss my point: most people who write [i]exclusively in modern C++[/i] would [i]not[/i] consider using a library written in C as an advantage; if you are talking about performance you [i]might[/i] have a point, but from most of the 2D benchmarks I've seen SFML performance parodies that of SDL, or even exceeds it. Also, writing (and maintaining) an object-oriented wrapper is [i]not[/i] the first thing a person wants to do once they pick a library. SFML is to C++ as SDL is to C, in my opinion. Sure, free functions and structs are still valuable parts of C++, but they are superseded by many of its other facilities. If I were to write a 2D game in C I wouldn't write a non-object-oriented wrapper around SFML, I would just use SDL. If I were to write a 2D game in C++ I wouldn't write an object-oriented wrapper around SDL, I would just use SFML. [editline]26th December 2013[/editline] Also, I'm not "complaining" about SDL in any way; it's a great C library. Unfortunately being a great C library does not mean it is a great C++ library, and that's all I mean to say.
Writing a full-on C++ wrapper for SDL would certainly not be a good task if you intend to just use SDL for some purpose other than to build a C++ wrapper. That said, C++ does make it easy to strap the required functionality of a C interface to modern C++ concepts if you don't need 100% encapsulation of the C interface. Wrapping a C++ interface not making (full) use of modern C++ to actual modern C++ often requires more work. It feels less like working with the interface as more like working around it. At least it seems so to me - maybe I'm just not aware of useful tricks there. On top of my head are third party shared pointers implementations and accepting pointer-arguments (or even worse: returning pointers) where a reference would be sound.
[QUOTE=ZeekyHBomb;43316532]Writing a full-on C++ wrapper for SDL would certainly not be a good task if you intend to just use SDL for some purpose other than to build a C++ wrapper. That said, C++ does make it easy to strap the required functionality of a C interface to modern C++ concepts if you don't need 100% encapsulation of the C interface. Wrapping a C++ interface not making (full) use of modern C++ to actual modern C++ often requires more work. It feels less like working with the interface as more like working around it. At least it seems so to me - maybe I'm just not aware of useful tricks there. On top of my head are third party shared pointers implementations and accepting pointer-arguments (or even worse: returning pointers) where a reference would be sound.[/QUOTE] When using shared pointers to manage object lifetimes, though, what are the advantages to accepting/returning a reference? If you see: [code] Foo &getFoo(); [/code] and then attempt to store a pointer: [code] Foo *foo = &getFoo(); [/code] you have now nullified (no pun intended) the purpose of the smart pointer, correct? An interface like: [code] void setFoo(std::shared_ptr<Foo> foo); std::shared_ptr<Foo> getFoo(); [/code] is explicit about the use of smart pointers in managing objects. In cases where ownership is transferred it is even more explicit to use unique_ptr: [code] void setFoo(std::unique_ptr<Foo> foo); std::unique_ptr<Foo> getFoo(); [/code] Or do you mean just bare pointers? In that case I can see why it would be nicer to work with references. Or do I just not understand what you mean? I'm still really green when it comes to C++ and would be interested in an example of where references are appropriate.
One could argue that C libraries are more useful due most languages having FFIs.
[QUOTE=Rayjingstorm;43316808]When using shared pointers to manage object lifetimes, though, what are the advantages to accepting/returning a reference? If you see: [code] Foo &getFoo(); [/code] and then attempt to store a pointer: [code] Foo *foo = &getFoo(); [/code] you have now nullified (no pun intended) the purpose of the smart pointer, correct? An interface like: [code] void setFoo(std::shared_ptr<Foo> foo); std::shared_ptr<Foo> getFoo(); [/code] is explicit about the use of smart pointers in managing objects. In cases where ownership is transferred it is even more explicit to use unique_ptr: [code] void setFoo(std::unique_ptr<Foo> foo); std::unique_ptr<Foo> getFoo(); [/code] Or do you mean just bare pointers? In that case I can see why it would be nicer to work with references. Or do I just not understand what you mean? I'm still really green when it comes to C++ and would be interested in an example of where references are appropriate.[/QUOTE] Yes, bare pointers. And there are situations where a reference is more appropriate than a shared pointer, although a bit more "dangerous". When you get a reference, it means that you don't own the object. That can also be done via a weak_ptr with the advantage that when the object gets deleted, weak_ptr will know that the object it is pointing to is not valid anymore, while the reference will just be an invalid reference that will be dangerous to use. The disadvantage is, that it is slightly[1] less efficient, because the shared_ptr and weak_ptr rely on an additional structure allocated on the heap and reference counting, while the reference is just a pointer in the binary with no extra code. When you can ensure that you will only keep(/use) the reference while the owner keeps the referenced object, the reference will never be invalid. [1]: probably; never benchmarked it or read about a benchmark. Lots of copying the shared_ptr whilst dealing with lots of memory invalidating the cache would make the access to that heap-allocated structure visibly loose performance I guess. A shared_ptr is also uses ever so slightly more memory than a plain reference/pointer, but this should be negligible unless you use many different shared_ptrs (i.e. to different objects) or work with tight memory constraints. The compiler might also be able to optimize some references out. Not sure how much overhead can be removed if a shared_ptr is used.
[QUOTE=Jookia;43317136]One could argue that C libraries are more useful due most languages having FFIs.[/QUOTE] I don't fully understand FFIs and that kind of stuff, but doesn't C++ (and any language with FFI implemented for that matter) support it the same?
The problem with calling into C++ is that compilers mangle the symbols differently. For C it's just the function name, in C++ the symbol includes things like parameter-types (this for example is what enables use of function overloading; see c++filt). And beyond that, if you intend to use C++ objects in the other language you will have to know how the compiler implemented things like virtual functions. I think C compilers could also mangle names while abiding to the standard. It's just that no one does it. And it seems that C++ compiler vendors can't agree on a ABI to use. You can make assumptions, such as on Windows you will expect the library to be compiled with MSVC and on Linux, OS X, *BSD you expect libraries to be built with gcc (that should work with clang, too. I'm pretty sure it does or tries to do what gcc does). That will work mostly fine, except when it doesn't. And like I said, while (I think) C compilers are also free to do funky stuff, they don't. And when it breaks you can (more or less) consider that a bug of the compiler used.
If you're writing C++ that you want to call from another language you're essentially forced to strip the interface down to C. The interface shouldn't contain exceptions, overloaded functions, templates and preferably not even class methods. (Though on Windows you can use SEH for language-agnostic exceptions) There's no way a completely different language should be expected to communicate with C++, seeing how even C++ runtimes have trouble understanding themselves.
I agree that everyone's points are valid about why a C library can be considered superior to an equivalent C++ one, but they all miss the qualification that you are already writing in C++. If you already made the leap from C to C++, you probably did it for some well-considered reasons which you decided outweigh the negative aspects of the language. Sure a C library may be more portable or more efficient, but in making your choice to write in C++ in the first place you may have already decided that these things are not as important as development time, or some other quality you look for in your language. As for name mangling and FFI I'm not so sure when these would come into play for a userspace game program. Nevertheless its a valid point.
You can, like ThePuska said, provide a public interface in C, although the actual logic and stuff is written in C++. [url=http://kcat.strangesoft.net/alure.html]ALURE[/url] is one example for a library that does that.
I'm gonna be posting the exercises I do here so you guys can tell me what I'm doing wrong and what I could be doing better so I can learn to be a better programmer and utilize c++ more efficiently. Someone told me that posting your code for others to critique is an excellent way of improving. (: [code]/* ---Exercise 6--- Write a program that asks the user to type an integer N and computes the sum of the cubes from 5^3 to N^3. */ #include <iostream> using namespace std; int cubed(int n) { return n * n * n; } int main() { int n(0), i(5), sum(0); while (n <= i) { cout << "Enter an integer greater than 5: "; cin >> n; } for (i; i <= n; i++) sum += cubed(i); cout << sum << "\n"; return 0; }[/code] [editline]27th December 2013[/editline] I really feel like I could shorten this code.
In your for loop it feels weird to just have an i in the initialization part, you can just do this: [cpp]for(;i <=n; i++)[/cpp] but I think that's just personal preference. However, instead of initializing i so far up I would have done a check against 5 rather than i, and initialized i in the for loop. I think it would be more readable that way. Also you can use pow instead of your cubed function [url]http://www.cplusplus.com/reference/cmath/pow/[/url]
for (i; i <= n; i++) sum += cubed(i); I would suggest not doing that. Very few people prefer it this way. Most people will find your code to be less readable if you omit your accolades.
Suppose I had an array of chars: [code] char charArray[] = {'H','E','L','L','O','\0'}; [/code] Now how could I write a c-styled string over that array? [code] char charArray[] = {'H','E','L','L','O','\0'}; char* overWriteThis = "ABC"; [/code] So the array would turn into: [code]'A','B','C','\0,'O','\0'[/code] I know this is a very unsafe way of writing stuff but it doesn't matter. I tried de-referencing the array elements and using memset but I couldn't get anything to work.
[QUOTE=mobrockers;43326295]for (i; i <= n; i++) sum += cubed(i); I would suggest not doing that. Very few people prefer it this way. Most people will find your code to be less readable if you omit your accolades.[/QUOTE] what do you mean? [editline]27th December 2013[/editline] and is this better? [code]int main() { int n(0), sum(0); while (n <= 5) { cout << "Enter an integer greater than 5: "; cin >> n; } for (int i = 5; i <= n; i++) sum += pow(i, 3); cout << sum << "\n"; return 0; }[/code]
[QUOTE=NixNax123;43326519]what do you mean? [editline]27th December 2013[/editline] and is this better? [code]int main() { int n(0), sum(0); while (n <= 5) { cout << "Enter an integer greater than 5: "; cin >> n; } for (int i = 5; i <= n; i++) { sum += pow(i, 3); } cout << sum << "\n"; return 0; }[/code][/QUOTE] That is what I mean. Clearly define your scope so everyone knows exactly what's going on. It will make your code more clearer. I personally also prefer an empty line after a method header but the opinion on that is a bit more divided than on accolades.
[QUOTE=NixNax123;43326519]what do you mean? [editline]27th December 2013[/editline] and is this better? [code]int main() { int n(0), sum(0); while (n <= 5) { cout << "Enter an integer greater than 5: "; cin >> n; } for (int i = 5; i <= n; i++) sum += pow(i, 3); cout << sum << "\n"; return 0; }[/code][/QUOTE] Completely unrelated, but I wonder if you could write it as: [code] for (int i = 5; i <= n; sum += pow(++i, 3)); [/code] ? [B]Edit:[/B] Seems to be valid.
[QUOTE=ollie;43326456]Suppose I had an array of chars: [code] char charArray[] = {'H','E','L','L','O','\0'}; [/code] Now how could I write a c-styled string over that array? [code] char charArray[] = {'H','E','L','L','O','\0'}; char* overWriteThis = "ABC"; [/code] So the array would turn into: [code]'A','B','C','\0,'O','\0'[/code] I know this is a very unsafe way of writing stuff but it doesn't matter. I tried de-referencing the array elements and using memset but I couldn't get anything to work.[/QUOTE] Something like this maybe? Just wrote this on the spot, so no guarantees it works out of the box. It should give you an idea of how to do it though. [code]char charArray[] = {'H','E','L','L','O','\n'}; char* overwriteThis = "ABC"; int i=0; int alen = 6; // Change this to a better way to get the array length. I can't recall the array length command in C off-hand. for (; i < alen; i++) { charArray[i] = overwriteThis[i]; } // Final result: charArray = {'A','B','C','\0','O','\n'}[/code] Then you can do something about changing the last char to your null character. This is, of course, assuming ANSI C. In which case, you just need to keep in mind that arrays and pointers are treated the same way, and that a [b]char[] str = {'H','i','\0'};[/b] is equivalent to a [b]char* str = "Hi";[/b]. The consequence of this, of course, being that you can array-iterate over a char*, character by character, just like an explicit array. And if you wanted to get fancy, you could pointer-iterate as well, though I personally don't much care for that method.
[QUOTE=Gmod4ever;43326723]Something like this maybe? Just wrote this on the spot, so no guarantees it works out of the box. It should give you an idea of how to do it though. [code]char charArray[] = {'H','E','L','L','O','\n'}; char* overwriteThis = "ABC"; int i=0; int alen = 6; // Change this to a better way to get the array length. I can't recall the array length command in C off-hand. for (; i < alen; i++) { charArray[i] = overwriteThis[i]; } // Final result: charArray = {'A','B','C','\0','O','\n'}[/code] Then you can do something about changing the last char to your null character. This is, of course, assuming ANSI C. In which case, you just need to keep in mind that arrays and pointers are treated the same way, and that a [b]char[] str = {'H','i','\0'};[/b] is equivalent to a [b]char* str = "Hi";[/b]. The consequence of this, of course, being that you can array-iterate over a char*, character by character, just like an explicit array. And if you wanted to get fancy, you could pointer-iterate as well, though I personally don't much care for that method.[/QUOTE] IIRC any string defined on compile time is actually a const char*. So you shouldn't overwrite it as it gets put into a special part of the process memory. You should use strcpy and put it into another pointer allocated at runtime and overwrite parts of that one.
[QUOTE=Gmod4ever;43326723]Something like this maybe? Just wrote this on the spot, so no guarantees it works out of the box. It should give you an idea of how to do it though. [code]char charArray[] = {'H','E','L','L','O','\n'}; char* overwriteThis = "ABC"; int i=0; int alen = 6; // Change this to a better way to get the array length. I can't recall the array length command in C off-hand. for (; i < alen; i++) { charArray[i] = overwriteThis[i]; } // Final result: charArray = {'A','B','C','\0','O','\n'}[/code] Then you can do something about changing the last char to your null character. This is, of course, assuming ANSI C. In which case, you just need to keep in mind that arrays and pointers are treated the same way, and that a [b]char[] str = {'H','i','\0'};[/b] is equivalent to a [b]char* str = "Hi";[/b]. The consequence of this, of course, being that you can array-iterate over a char*, character by character, just like an explicit array. And if you wanted to get fancy, you could pointer-iterate as well, though I personally don't much care for that method.[/QUOTE] You want the string/smaller length there, (alen = 4 instead of 6) or the program can segfault or return undefined data. [editline]27th December 2013[/editline] Definitely check for the smaller length, or there's an overflow vulnerability. [editline]27th December 2013[/editline] [QUOTE=commander204;43326792]IIRC any string defined on compile time is actually a const char*. So you shouldn't overwrite it as it gets put into a special part of the process memory. You should use strcpy and put it into another pointer allocated at runtime and overwrite parts of that one.[/QUOTE] The variables are named confusingly, clearer would be writeThisOver instead of overwriteThis.
[QUOTE=Tamschi;43327099]The variables are named confusingly, clearer would be writeThisOver instead of overwriteThis.[/QUOTE] I think overwrite this makes more sense than write this over.
[QUOTE=commander204;43326668]Completely unrelated, but I wonder if you could write it as: [code] for (int i = 5; i <= n; sum += pow(++i, 3)); [/code] ? [B]Edit:[/B] Seems to be valid.[/QUOTE] That's what I'm talking about! YES! I love learning little quirks like this that makes my code shorter and easier to read. Thanks a bunch! [editline]27th December 2013[/editline] [QUOTE=mobrockers;43326656]That is what I mean. Clearly define your scope so everyone knows exactly what's going on. It will make your code more clearer. I personally also prefer an empty line after a method header but the opinion on that is a bit more divided than on accolades.[/QUOTE] Okay! Thanks!
[QUOTE=NixNax123;43327178]That's what I'm talking about! YES! I love learning little quirks like this that makes my code shorter and easier to read. [/QUOTE] Shorter yes, easier to read: not at all. There's really no point making these tiny code length optimizations because in the end the binary will be the same. Sure you can optimize it if it's gonna make your calculations faster but i find that the code just becomes much harder to manage. Compilers are beasts at optimizing calculations just so you don't have to.
[QUOTE=WTF Nuke;43327167]I think overwrite this makes more sense than write this over.[/QUOTE] The variable isn't overwritten though. "Overwrite this" and "write this over [...]" are opposites in direction. Naming it replacement would probably a good idea.
[QUOTE=ollie;43326456]Suppose I had an array of chars: [code] char charArray[] = {'H','E','L','L','O','\0'}; [/code] Now how could I write a c-styled string over that array? [code] char charArray[] = {'H','E','L','L','O','\0'}; char* overWriteThis = "ABC"; [/code] So the array would turn into: [code]'A','B','C','\0,'O','\0'[/code] I know this is a very unsafe way of writing stuff but it doesn't matter. I tried de-referencing the array elements and using memset but I couldn't get anything to work.[/QUOTE] [code]// if the length of the new string (with the null terminator) fits in the char array, overwrite it if (strlen(overWriteThis) < sizeof(charArray)) { strcpy(charArray, overWriteThis); } else { // Doing strcpy would overflow the buffer. }[/code]
If you're using C just use [URL="http://www.cplusplus.com/reference/cstring/strncpy/"]strncpy[/URL] [code] char charArray[] = {'H','E','L','L','O','\n'}; char* overwriteThis = "ABC"; strncpy(charArray, overwriteThis, sizeof(charArray) / sizeof(char) - 1); [/code] srncpy will not null terminate a string if the length of the src >= dest, so to be safe (and ensure the final string is null-terminated) I'd just pass in the length of dest - 1, so that it always ends up with at least 1 null terminator. [editline]27th December 2013[/editline] ninjad :v: [editline]27th December 2013[/editline] ThePuska's solution is definitely better if you want to be able to react to an overflow, as mine will just truncate the copy silently.
Has anybody here done any Android development? I have a fair amount of experience, but this is the first time I've worked with canvas, and I'm having what looks like scaling issues. Following the documentation, I have created a view class which extends the SurfaceView class. I get the holder as usual and draw to the canvas provided by locking the holder. However, in the two apps I've written that utilize canvas, everything I draw to the canvas appears scaled up. Here's a picture for example. [img]http://i.imgur.com/AIWd2gZ.png[/img] The top left view is the canvas. Clearly, the rounded corners are blurry/low res. This is with AA applied. The line through the middle is supposed to be hairline. What's going on here?
Sorry, you need to Log In to post a reply to this thread.