# Off-Topic Discussion > The Lounge > Ask/Tell Me About >  >  Ask me about C / C++

## ninja9578

I know there are a lot of people trying to learn C++ on this forum.  I'm a professional C++ programmer, and it's an enormously complex language so ask me anything.  There are lots of things you need to know to write good C++ code: iterators, inheritance, OOP, procedural programming, static and dynamic functions, macros, scope, consts, virtual methods, encapsulation, pointers, null objects, threading, mutexs, cross platform, callbacks.

----------


## The Invisible Man

I have a console application using a case block to open some files. I just need the syntax for an 'open file' command.

----------


## Dairyman

Can I ask, is this only with C++ or other C languages too?

EDIT-
Also, do compiled C++ programs have to run on an IDENTICAL system? (Same operating system, same CPU etc) I read this in an e-book once and switched back to Visual Basic.

----------


## ninja9578

> I have a console application using a case block to open some files. I just need the syntax for an 'open file' command.



Ugh, files are a pain.  There are good libraries out there (I use wxWidgets,) but pure C is hard.



```
FILE* file = fopen("yourfile", "w");  //w for write, r for read, a for append
if(file!=NULL){
  /*
    fwrite and fread are what you need
    fwrite(buffer, size of element, number of elements, file pointer)
  */
  size_t check =  fwrite("Stuff to write", sizeof(char), 14, file);
  if (check != 14) printf("Writing failed");
}
fclose(file)
```






> Can I ask, is this only with C++ or other C languages too?



I only know C and C++, I don't know C# or objective C.





> Also, do compiled C++ programs have to run on an IDENTICAL system? (Same operating system, same CPU etc) I read this in an e-book once and switched back to Visual Basic.



Yes, that's no different than any other programming language that does native compiling.  A program written in C++ or C compiled on OSX will only run on OSX, Windows programs will only run on Windows.  CPU doesn't matter... mostly  (AMD=AMD64=Intel=Intel64!=PPC)

It's very easy to fix though, a few preprocessor commands will allow you to compile on any system.

----------


## The Invisible Man

Crap, I meant C++. Sorry, but... um.... yeeeeeeeeeeeeaaaaaaaaaaah. Could I get that the Open File command on C++? Command for the Standard Library?

----------


## ninja9578

Yes, but it's in a different library in C++, I think it's in <iostream>

----------


## The Invisible Man

I have <iostream> and <stdlib.h>. What's the command?

----------


## ninja9578

They are the same as C.  C++ is a [nearly] complete superset of C.

----------


## mrdeano

What language did you learn before C & C++?

----------


## ninja9578

Basic and assembly.

----------


## The Invisible Man

So you're saying


```
#include <iostream>
#include <stdlib.h>
int main()
{
FILE* file = fopen("yourfile", "w");  //w for write, r for read, a for append
if(file!=NULL){
  /*
    fwrite and fread are what you need
    fwrite(buffer, size of element, number of elements, file pointer)
  */
  size_t check =  fwrite("Stuff to write", sizeof(char), 14, file);
  if (check != 14) printf("Writing failed");
    fclose(file)
                  }
}
```


This is what I _type_ into my *IDE* to open the file/app/.exe?

Sorry to bug you like this, but I'm not sure if you were answering my question.

----------


## ninja9578

Yes, that's how you open a file, write the words "Stuff to write" to it, and then close it again.  :smiley:

----------


## Replicon

You can do file i/o the fstream way too, which is usually cleaner.

----------


## peacock486

let's just say this.  it's "has an ass rocket, kills self, and goes to hell" (AKA Infinity) hard.

68000 ASM is probably easier.

----------


## Man of Steel

An idea I just had regarding ebooks and the library system led me here...

Say a library wanted to set up a proprietary program and ebook format to offer ebooks from their website that could be downloaded, but would 'expire' in a set period—say 30 days. This way they could offer the same selection for download as they did at the physical location, but on the same principle. Would C or C++ be the preferred method of designing said program, or would another method be better? At the simplest level, what would be involved in something like this?

Just a thought I had, while I was wishing I could just download any book I wanted to read—legally.

----------


## pepolshet

*cough* warez-bb *cough*  ::D:

----------


## Sornaensis

> Crap, I meant C++. Sorry, but... um.... yeeeeeeeeeeeeaaaaaaaaaaah. Could I get that the Open File command on C++? Command for the Standard Library?






```
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
    fstream FILE("foo.txt",ios_base::trunc); //First, we open a file named "foo.txt", overwriting any existing data. (signified by ios_base::trunc for truncate ;))
    
    if(!FILE.is_open();){ //If the file opens, then continue
        FILE<<"Stuff to write\n"; //Write to the File stream using the insertion operators <<
        string In;
        FILE>>In; //Read from the stream using the extraction operators >>
    }
    return EXIT_SUCCESS; //Because macros are just way cooler than constants
}
```

----------


## Ynot

> An idea I just had regarding ebooks and the library system led me here...
> 
> Say a library wanted to set up a proprietary program and ebook format to offer ebooks from their website that could be downloaded, but would 'expire' in a set periodsay 30 days. This way they could offer the same selection for download as they did at the physical location, but on the same principle. Would C or C++ be the preferred method of designing said program, or would another method be better? At the simplest level, what would be involved in something like this?
> 
> Just a thought I had, while I was wishing I could just download any book I wanted to readlegally.



Better reduce the "loan time" on those
anymore than 48 hours and you risk having your "restriction" cracked

Something like an expiring book just wouldn't work....
I know you know better than this,
but anyhow

Step though the program with a "legitimate" book
Step though the program with an "expired" book
find the fork
redirect the expired fork down the legitimate fork

In all honesty, kids stuff

As a book publisher, you have just spent god-knows how much money buying this DRM mechanism from someone, and it's cracked in hours

About the only way to realistically overcome this, is to require authorisation over the internet each time you open an e-book
which would be crap, and only annoy people

The "loaning" of things is a mechanism devised in the physical world of scarce products that cost money to reproduce
It doesn't translate (sanely) over into the digital world

----------


## Man of Steel

> Better reduce the "loan time" on those
> anymore than 48 hours and you risk having your "restriction" cracked
> 
> Something like an expiring book just wouldn't work....
> I know you know better than this,
> but anyhow
> 
> Step though the program with a "legitimate" book
> Step though the program with an "expired" book
> ...



Aye, I agree/know that, realistically speaking, it would never work. Just wishful thinking, really, and thought it posed an interesting hypothetical question for this thread. I guess the more practical way to do something of that nature would be via the internet, using Flash to prevent easy copy & pasting. Even that would be less than ideal, of course. 

*sigh*

----------


## ninja9578

Yes, C++ is the most powerful language that there is, you can use it for something like that.  However, I wouldn't use a timestamp, seeing as people can change their system time.  I remember Apple having a problem with people renting movies on iTunes and then setting back their clocks.

----------


## mrdeano

Hey, I am trying to cover the basics of C++.
I think I have some of them down, I just need to double check if I'm right.




```
#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    cout << "Here is some text";
    cout << endl;

    cout << "What is 15 + 17? the answer is:";
    cout << 15 + 17;

    cin.get();
    return 0;
}
```


Above is the first code I have written for C++, I found a little beginners tutorial for it. It is important to understand the code, so here it goes.




```
#include "stdafx.h"
#include <iostream>
```


They tell the compiler to include these in the .exe
They are both separate files containing code.
stdafx.h is a header code and isostream contains different packages that do several things.




```
using namespace std;
```


Tells the computer that it wants to use the package 'std' from ;isostream




```
int main()
```


Is the main function which every piece of code should have.




```
{
```


Opens the code.




```
cout << "Here is some text";
```


'cout <<' gives the program a output, or something to print. In this case its a line of text.
Cout is a keyword taken from the package 'std' which is in 'iostream;




```
cout << endl;
```


'endl' ends the line




```
cout << 15 + 17;
```


This tells the computer to print the answer of this calculation. 




```
cin.get();
```


This makes the program wait for an input by the user




```
return 0;
```


Once it has the input, it tells the computer to revert back to what it was doing before hand




```
}
```


closes code




I was wondering if you could check if I have it all right.
If there's anything I am missing as a beginner.. I would appreciate it if you point it out  :smiley: 


thanks  :smiley:

----------


## ninja9578

> ```
> using namespace std;
> ```



 ::microwave:: 





> ```
> #include "stdafx.h"
> #include <iostream>
> ```
> 
> 
> They tell the compiler to include these in the .exe
> They are both separate files containing code.
> stdafx.h is a header code and isostream contains different packages that do several things.



Yes.





> ```
> using namespace std;
> ```
> 
> 
> Tells the computer that it wants to use the package 'std' from ;isostream



... kind of...  That tells it to use the std namespace throughout the program.  It is considered better programming technique to only have a namespace over small scopes.  It actually allows you to transcend scope, this is very useful in large programs so that you don't have duplicate variables and have to worry about concurrency.





> ```
> int main()
> ```
> 
> 
> Is the main function which every piece of code should have.



Yes, it's the entry point of the operating system, there is more to it, but you don't need to know that unless you are doing assembly optimizations.





> ```
> cout << "Here is some text";
> ```
> 
> 
> 'cout <<' gives the program a output, or something to print. In this case its a line of text.
> Cout is a keyword taken from the package 'std' which is in 'iostream;
> 
> 
> ...



Yes, cout is a stream that goes to the terminal, the real thing that you need to take away from that line is the << operator.  There are lots of functions that use it, you can create classes and use STL libraries to send strings through pipes, files, even the internet.

endl is a std const for cross compatibility, most programers use \n instead though, even though we shouldn't  :tongue2: 





> ```
> cin.get();
> ```
> 
> 
> This makes the program wait for an input by the user



Yes, more specifically keyboard input, inputs from other devices won't trigger this method.





> ```
> return 0;
> ```
> 
> 
> Once it has the input, it tells the computer to revert back to what it was doing before hand



Kind of, it tells the operating system to close the program and return an error code of 0.  Returning things other than zero from the main loop tells the operating system that something went wrong, and depending on the code and the OS, it may attempt some type of recovery.  From -127 to -1, the system may try a recovery, from 1 to 127, it is a user-defined error and will not produce any type of recovery on the OS level, it may be read by a calling or forking program though.

----------


## starry eyes

I have a package called "atomic parsley". Instead of a make file, it has a shell script with commands to compile each unit without linking, then goes through a second time and links everything. Each source file seems to have all the includes it needs, as-is. But on the compile w/o linking stage, it's using g++ with command line options which I don't know the importance of, which fail with a syntax error on all the c compilers I've got, even the version of gcc I have.

Are there any quick guides to creating a proper make file for projects lacking one?

----------


## ninja9578

Ouch, creating makefiles for large projects suck  :Sad: 

What options are being set that you don't know the significance of?  Most likely the problem is that the program was written in Visual C++ and not GNU C++.  M$ doesn't adhere to C++ standards, so their software won't work in other compilers, that's why so few people write in Visual C++ outside of M$ itself.  

The basic makeup of a makefile is setting the flags to variables, the creating a command for each file.  Here's a good tutorial.

What options were being set that you didnt' understand?

The most common ones are:
-c : compile, but don't link
-O1, O2, O3, Os : optimization levels
-strip : strip unnecessary symbols and code
-o : send to this output file
-l : link a library
-I : include paths
-g : include debugging information it the executable
-Wall : *W*arnings *All* - warns you about everything

----------


## starry eyes

Yes, I've been figuring that this will suck. But I really need some kind of code for dumping itunes m4a tags to a plain text file  :Sad:  Besides the gcc that came with the linux I'm using, I've got borland c++ and symantec c++ for windows. 
I got them back when I was taking some classes in C programming.

There is a command line in the shell script similar to this for each source file during the compiling stage-

g++ -g -O2 -Wall -MT obj_files/AP_commons.o -MD -MP -MF
"./obj_files/AP_commons.Tpo" -c -o obj_files/AP_commons.o
AP_commons.cpp

Each of those compile commands gets the following error message, and then doesn't produce any output file-

g++: cannot specify -o with -c or -S and multiple compilations

When the link command is run later, there's nothing to link.

----------


## ninja9578

That's because your syntax isn't quite right.  Try this:




```
obj_files/AP_commons.o: AP_commons.cpp
   g++ AP_commons.cpp -g -O2 -Wall -MT obj_files/AP_commons.o -MD -MP -MF
"./obj_files/AP_commons.Tpo" -c
```


You can't specify where to compile to in the compile line itself, instead you tell it what output file the compile line belongs to.

The syntax for compiling only goes:



```
Target: All dependancies (including libraries)
   compiler command
```

----------


## starry eyes

> That's because your syntax isn't quite right.  Try this:
> 
> 
> 
> 
> ```
> obj_files/AP_commons.o: AP_commons.cpp
>    g++ AP_commons.cpp -g -O2 -Wall -MT obj_files/AP_commons.o -MD -MP -MF
> "./obj_files/AP_commons.Tpo" -c
> ...



That one didn't work either  :Sad:  g++ thought the *.0 and *.Tp0 were the input files and said it couldn't find them.

I noticed that I couldn't find any place where it actually used the *.Tpo files, so I experimented this morning with a very simple command line of 
g++ AP_commons.cpp -c
then moving the *.o files to obj_files manually. That cured most of the problems.

But then I discovered that g++ couldn't find lroundf in the math library, even though it's there just as much as the other math functions the code uses. Fortunately it was simple to replace lroundf with the expression of (int)(n+0.5)

After that, g++ couldn't find the system getopt.h, even though it's just as much there as any of the other system inlcudes. So I had to specify the absolute file location in the source code.

But now, the g++ linking stage can't find getopt_long in getopt.h, even though it is there. And I have no idea how to fix that  :Sad:

----------


## starry eyes

Ninja,
since that package refused to compile, and unfortunately your advice didn't work, I spent yesterday afternoon coding a m4a tag dumping program from scratch in VB. It doesn't allow tag editting or anything, but it runs and serves the purpose I needed it for. So that's all taken care of. Maybe I'll even rewrite it in (working) C code when I have more energy, doing that should at least speed it up and allow me to port it into linux too.

----------


## ninja9578

Yep, C code runs circles around VB code.

----------


## SuperSmashcz

Okay so I've started writing my own 3D engine in C++.. it's got a terrain engine and lighting.. ect. How do I take all my classes and turn it into a library? So like i could be like DDHI_MakeTerrain(..) rather than being like including the classes and calling MakeTerrain(..) Basically.. i could wrap up all my classes and import them all using a single .lib and use it throughout other programs i write using those classes?

----------


## ninja9578

It depends on your platform and compiler.

First thing that you need to do is declare all of the methods that you want to use as static stdcall.  You can't use classes directly, you need to write an interface.  something like this:




```
//This is the interface header, compiled with both your library and your program
#include "yourclass.h"

static __stdcall void * New(void){
   return (void*)new yourclass();
}

static __stdcall SomeMethod(void * handle, int other_params...){
   if (handle){
      yourclass * pthis = (yourclass *)handle;
      pthis -> SomeMethod(other_params...);
   }
}
```


Then you need to set up your IDE to spit out a dll instead of an exe.  It depends on your IDE on how to do that, if you're using a makefile, then you have to figure it out yourself, I don't deal with makefiles anymore  :tongue2: 

You may or may not need to create and define a DEF file, all that does is tells the compiler what the names of the exported methods are.

Most compilers will spit out both a dynamic and a static library, dynamic ones are probably better because you can change your engine on the fly.  That's how games that use both OpenGL and DirectX do it.

----------


## Flavour of Night

> Yep, C code runs circles around VB code.



Damned straight.  Once compiled, does VB still toss in enormous wodges of non-essential crap from over-stuffed libraries?

----------


## ninja9578

Not really, it's fairly compressed.  There is some overhead, for instance, strings have about 4 levels of abstraction around then so every string manipulation requires about 4 times the work as in C++.  VB is designed to be a learning tool, not a professional programming app, so the compiler is not very efficient at optimizing.

----------


## Keresztanya

What is the best book on C to read?

----------


## ninja9578

"The C Programming Language"

----------


## Flavour of Night

> Not really, it's fairly compressed.  There is some overhead, for instance, strings have about 4 levels of abstraction around then so every string manipulation requires about 4 times the work as in C++.  VB is designed to be a learning tool, not a professional programming app, so the compiler is not very efficient at optimizing.



I can still remember compiling "Hello World" for lulz in the old QB 4.5.. 14 Kb for:  print "Hello World!"

C compiled it much tighter only needing the include for stdio.h for the printf.

Doing it in my old Borland Assembler only took a handful of bytes once compiled and linked to knock out a .com file with a label of:

_mssg  db 'Hello World!",13,10,'$'_

then nothing more than:

_lea dx, mssg
mov ah, 4ch
Int 21_

Those DOS calls sure are handy.  You could do it also with Int 9, but that's a bit more work.

After awhile, you'd start to recognize the actual machine code for some of the calls and the like.

Seems silly now, but, I can lay claim to having once owned a 10 meg HD, so the "who cares" attitude of today was a luxury unaffordable back then.

code is fun, I've not bothered with it in years.. kinda makes me want to get my fingers back in shape.  :smiley: 

.

----------


## ninja9578

Good for you.  I grew up with some less than optimal machines and I got really good at doing optimizations, I still do it.  Qbasic was fun  ::D: 




```
? "QBasic is awesome!"
```

----------


## khh

How do you find the execution time and memory imprint of your code?
(I'm using windows, btw)

----------


## ninja9578

Your memory imprint should be visible in your Task Manager (ctrl+alt+del)

As for execution time, all you need to do it have your program record the time when it starts, then record it again when it quits.  Subtract the two and print the result  :smiley:

----------


## Kastro187420

I've always been interested in learning C/C++, but could never find any good reference/learning sources.

Having an understanding of php and some sql (basic sql functions such as update/insert/delete/drop, enough to maintain a database), aswell as basic Javascript, how hard do you figure it would be to move into the C languages?

----------


## Grunkie7

This question is more programming in general but still applies to C. 

I've got a shelf chocked-full of programming books from my brother collected during his college years.  Java, C, C++, Python, etc..  Thing is, "Horton's Beginning Java" for example, is a massive book, but it's from 1997.  Same with most of the other books (give or take a few years).  Have things in the programming world changed enough in the past 12 years to make these books obsolete/incompatible or have they remained fundamentally the same?
The book cover on my example states '_covers JDK 1.1_'  ::chuckle:: 

I have a feeling I aughta move into something more universal; Most of my programming experience is in learning Actionscript out of a 'game programming for dummies' book.  :Oops:

----------


## ninja9578

The only major change in programming fundamentals is the emphasis on cross-platform programming.  The skyrocketting sales of Macs made companies rethink how they designed software since more and more companies were demanding Mac-friendly apps.  Because OSX is UNIX based, a side-effect of that was a surge in Linux programming.

C99 made some big changes.  For instance, optional parameters are not preferred over method overloading.  You are guaranteed a few more things, and the use of reference counting has increased.  That is unless you are using Visual C++.  Visual C++ does not adhere to the C++ standards, which is why so few people use it.

----------


## gagaku

where can I find a good free C++ compiler that I don't need to register?

----------


## ninja9578

Most C++ compilers are free, ones that you have to pay for are a scam.  The standard is GNU, which is 100% free.

If you download XCode, the gnu compiler will come with it.
If you're Linux, gnu c++ is preinstalled on your machine
For Windows download Code::Blocks, the compiler comes with it.

----------


## khh

If you're on windows and don't want an IDE, just a compiler, then you can download mingw. I'm guessing that's the compiler Code::Blocks use.
Microsoft also provide a free compiler, Visual Studio Express, which I think you can get without registering (it includes an IDE)

Also, ninja, I have a question: If you're dabbling in programming and have learned some C++, do you think it would be a good idea to read up a bit on C too? Would it be useful?

----------


## ninja9578

Yes, C++ is a superset of C, so knowing C will be good for C++.

----------


## khh

> Yes, C++ is a superset of C, so knowing C will be good for C++.



I know that C is still used a lot in embed devices, and I think it's pretty much used to write drivers too. Does C have any other major uses?
Cause for regular application development, I think other languages like C++ have the edge.

----------


## ninja9578

It depends on what the application is.  Huge applications use C++ because it's easier to write object oriented programming.  C has a major advantage of speed though.  Games and graphics programs are largely written in C and will be until the C++ optimizers can rival human C code in speed and efficiency.

Lots of programs are written in multiple languages and are heavily modularized.  I've written a few programs in both C++ and C.  C++ tends to be my framework, however I pull large chunks of it out and put them into dlls which I usually write in C.

----------


## khh

The other day I started wondering how scripting language interpretors are implemented. As I recall you've written quite a few of them. Do you think you could give me the general idea?

----------


## ninja9578

Well, they're surprisingly simple.  They are two parts, a parser, and a runner.  The parser converts them into a vector (I use a vector, could be any container) of strings.  Then have a compiler which converts them into more optimized code using callbacks and such.  So:



```
@If(@Add(1, 2) = 3, 
   ++%i%;
   ++%j%;
else
   --%i%;
)
```


Would get converted into five string vectors that would end up like this.



```
ID | Function | parameters                  | nextfunction
1:   @Add,      1, 2                          <back>
2:   @PreInc,   i                             <3>
3:   @PreInc,   j                             <back>
4:   @PostInc,  i                             <back>
5:   @If,       <1>, =, 3, <2>, <4>           <end>
```


Then run that set of vectors through a compiler which converts the command into a callback to a function and creates a class containing all of that information.  You also need a runner class which knows that <5> is actually the first one to be run.

Then when you run the thing, you start on <5>, calling the callback associated with it, and it analyzes each parameter, if it encounters a <#> it runs that command too.  Then after if does the first command (<5>) fully, it uses the next member to figure out which function goes next, if it's <back> or <end>, then it stops what it's doing and returns.


Weird, huh?  :smiley:

----------


## khh

> Weird, huh?



Yeah. That's not at all how I imagined they would work, but it seems fairly logical now that you present the idea. (Though I had to look spend some time just looking the code over and mentally executing it to get the picture :p)

How would you include user defined functions? One way of doing it could be to just paste the code for each time it's used (like inline functions), but how would you get proper functions?
Also, I'm guessing it would be pretty essential to implement a syntax checker?

----------


## Artelis

How do I write a callback function that will get called at a rate that I can define?

----------


## ninja9578

> Yeah. That's not at all how I imagined they would work, but it seems fairly logical now that you present the idea. (Though I had to look spend some time just looking the code over and mentally executing it to get the picture :p)
> 
> How would you include user defined functions? One way of doing it could be to just paste the code for each time it's used (like inline functions), but how would you get proper functions?
> Also, I'm guessing it would be pretty essential to implement a syntax checker?



I actually don't implement a syntax checker, my company has a dev-staging-live process, my app is live so it's assumed that everything is correct when it gets to me.

I do implement inline functions in that very way, and as for user defined real functions, well, my current language doesn't support those at this time, but I plan to add them in the very near future.  They aren't that difficult.  Basically, you would just replace a call to that function with something like @UserDefined(<place>) during a preprocessing pass.  Then when you compile your callbacks, you have it point to the function that you've defined.

Yeah, scripting languages are weird things, and difficult to start implementing, but once you've done a few of them, you can write pretty advanced ones really quickly.





> How do I write a callback function that will get called at a rate that I can define?



You mean in a scripting language, or in C++?

----------


## Artelis

> I actually don't implement a syntax checker, my company has a dev-staging-live process, my app is live so it's assumed that everything is correct when it gets to me.
> 
> I do implement inline functions in that very way, and as for user defined real functions, well, my current language doesn't support those at this time, but I plan to add them in the very near future.  They aren't that difficult.  Basically, you would just replace a call to that function with something like @UserDefined(<place>) during a preprocessing pass.  Then when you compile your callbacks, you have it point to the function that you've defined.
> 
> Yeah, scripting languages are weird things, and difficult to start implementing, but once you've done a few of them, you can write pretty advanced ones really quickly.
> 
> 
> You mean in a scripting language, or in C++?



in a scripting language...

Isn't this a C/C++ thread?! Why would I be asking questions that AREN'T about C or C++? Well anyway, I'd prefer it in C, but I'm pretty sure it'd be handled the same way in either. Callbacks don't really use classes from my knowledge.

----------


## ninja9578

Callbacks are just regular methods.  All a method is is a pointer to a bit of code, nothing more, so you can store a pointer to a method just like to store a pointer to an object.




```
someclass * a = new someclass();
someclass * b = a; // referencing a class
```





```
typedef int (*addcallback)(int, int);  //declare the type of callback and the parameters

int ADD(int a, int b){  //the actual method which you will be calling back to.
  return a + b;
}

//in anywhere else in the same namespace
addcallback add = ADD;  //make a reference to the method, just like you reference a class
int j = add(4, 5);  //use the callback just like you would any other method
```


What did you mean "that gets called at a rate that I define?"  You can call the callback whenever you'd like.

----------


## Ynot

function pointers are a good thing to get your head around for advanced stuff.
Function pointers are at the heart of both polymorphism and function overloading
you can do some seriously cool stuff with function pointers

----------


## ninja9578

> function pointers are a good thing to get your head around for advanced stuff.
> Function pointers are at the heart of both polymorphism and function overloading
> you can do some seriously cool stuff with function pointers



Also shared libraries.  Modularization is one of the most important things in advanced programming.  No big program is one big program, it's a little program and a multitude of helper dlls or sos.

----------


## khh

I'm looking for a cross-platform library implementing network connections, and a good guide on how to use it. If boost has such networking functionality that's be good.
Basically what I want is a library which already implements the whole TCP/UDP. I'm just looking to create some communication between a generic client and a generic server. Know where I can find that?

----------


## ninja9578

Yes, Boost has a network library.  Boost Network  :tongue2:  I've never used it, but I know that it exists and because it's Boost there are lots of tutorials for it.

----------


## Ynot

also have a look at QT
it's much more than a GUI layer
(in fact, you don't even have to use the GUI layer - you can just use the networking libraries)

----------


## ninja9578

wxWidgets too.  I prefer wx because it's got a huge community for support, whereas Qt used to be a commercial product, so support is limited.

----------


## ninja9578

I changed my mind about wxWidgets.  Don't use it, it's given me my last headache, I'm writing my own library from scratch, if anyone wants to help, let me know.

----------


## khh

Okai, I have a question... again :p

So in a recent school assignment I need to dynamically allocate a 2D table. I chose to do it like this:



```
int** table;
table = new int*[width];
for (unsigned n = 0 ; n < width ; ++n) {
	table[n] = new int[height];
}
```


(if there is a better way to do it, please tell me :p)

But I had a problem when I was deallocating the memory again. I had thought I could simply do it like this:



```
for (unsigned n = 0 ; n < width ; ++n) {
	delete[] table[n];
}
delete[] table;
```


but that frequently (though not allways) caused the program to crash, citing heap corruption as the cause. So why would the above crash the program, and how can I deallocate the memory?

(I realise the problem could be circumvented by allocating it as a 1D table, and write a function that can translate two coordinates to an index, but I want to know why the above doesn't work)

----------


## ninja9578

Well, there is a better way to do it, it's always best to allocate memory that goes together all at once.  Remember, using a C-cast you can change anything into anything else.




```
int** array = (int**)malloc(width * height * sizeof(int));
```


Then to delete it simply:



```
free(array);
```


 :smiley: 

Looking at your code at a quick glance, I don't see anything incorrect.  I would run it through the debugger and put a breakpoint on each delete[]  :smiley: 

Also, it's good practice to explicity declare what type you're using.



```
unsigned n = 0; //not standard C++
unsigned int n = 0;  //correct
```

----------


## khh

Wow, quick reply  ::D: 





> Well, there is a better way to do it, it's always best to allocate memory that goes together all at once.  Remember, using a C-cast you can change anything into anything else.
> 
> 
> 
> 
> ```
> int** array = (int**)malloc(width * height * sizeof(int));
> ```
> 
> ...



I have heard that it is good practise not to use the C functions in a C++ program, though I might have misinterpreted this. Would it be possible to use something like



```
int** array = static_cast<int**>(new int[width*height]);
delete[] array;
```


Also, how would that code know that I wanted a table of the dimentions width x height, and not height x width or something else entirely? I would want it to function identically to a static array that could be created with



```
int array[width][height];
```


 if width and height were constants.





> Also, it's good practice to explicity declare what type you're using.
> 
> 
> 
> ```
> unsigned n = 0; //not standard C++
> unsigned int n = 0;  //correct
> ```



Yeah, usually I define shorts like UINT in a header file. I did think that "unsigned" was standard C++ for "unsigned int", though, like "long" is standard for "long int". :p
But since you have pointed out it isn't, I'll try and use fully qualified variable names from now on :p





> Looking at your code at a quick glance, I don't see anything incorrect.  I would run it through the debugger and put a breakpoint on each delete[]



I just added a cout statement, and found that "delete[] table[0];" worked, and then it crashed on "delete[] table[1];" I tried having n count down from width-1 instead, but the result was the same, it crashed on the second deallocation.

----------


## ninja9578

No, using C functions is very common.  C functions are very very fast.  Don't use C _headers_.  ie #include <ctime> instead of #include <time.h>

Anyway, if I were you, I would write a structure to handle an array for you and a method to get specific items:




```
#include <iostream>

struct Array {
public:
    Array(unsigned int width, unsigned int height){
	   w = width; h = height;
	   array = (int*)malloc(width * height * sizeof(int));
    }
    ~Array(void){
	   free(array);
    }
    inline int & at(unsigned int x, unsigned int y){
	   assert(x < w);
	   assert(y < h);
	   return array[w * y + x];
    }
private:
    int * array;
    unsigned int w, h;
};

int main(){
    Array test(100, 150);
    test.at(12, 43) = 15;
    std::cout << test.at(12, 43) << std::endl;
    return 0;
}
```

----------


## ninja9578

Oops. I forgot a const at operator  :tongue2: 




```
    inline const int & at(unsigned int x, unsigned int y) const {
	   assert(x < w);
	   assert(y < h);
	   return array[w * y + x];
    }
```


Did you get how everything in my code works?  This is how arrays are done behind the scenes anyway and because it's just a wrapper and the only functions are inline, the compiler will probably optimize away the structure.

----------


## khh

Mostly, yeah. But I don't get why you use assert. I thought the point of an assert statement was to halt program execution. Would it not be more suitable to use an if statement?

Also, what does the const operators do in the last bit you posted? I have never learned to use them, except in variable declarations.

----------


## ninja9578

Yes, asserts halt operation, but only in debugging mode.  In release mode, they are compiled out, so no checks are done.  This helps you make your code correct before you release it.

const at the end of a function means that object that it's being called on will not change.  When variables are declared as const, it means that they can't be changed.  So you can only call const functions.




```
#include <iostream>

class foo {
public:
    foo(void){};
    ~foo(void){};
    void Test(void) const {
	   //not allowed to change anything in this class
	   std::cout << "Test const" << std::endl;
	   //bar = 1;  <- This is illegal
    }
    void Test(void){
	   //can manipulate the object
	   std::cout << "Test" << std::endl;
	   bar = 1; //This is fine
    }
private:
    int bar;
};

int main(){
    foo one;
    one.Test();  //foo is not const, so the non-const method will be called
    const foo two;
    two.Test();  //foo is const, so the const method is called
    
    return 0;
}
```

----------


## ninja9578

const essentially means "read only" so 
operator [] lets you read and write to the class
operator [] const lets you read from the class only

----------


## khh

Okai, I understand. Thanks  ::D:

----------


## slash112

I thought I should pop up a slightly old thread for this problem I'm having.

I started *trying* to use wxWidgets.
IT makes sense... a little bit.

But there is one roadblock in my way of progressing in a program I am trying to get done.

Basically, I want to be able to click a button (In this case, "Button2"), so that the text changes. I can do that fine. But I then want to be able to click it again so that it changes to something new.


I have tried countless different possible ways of what I thought would work, but I just can't get it.

This was my last attempt (The bit I'm at a problem with):




```
void Physics_StudyFrame::OnButton2Click(wxCommandEvent& event)
{
    for (int a=0; a<2; a++)
    {
        (StaticText2)->SetLabel(_("FirstClick new Text"));
        a = a + 1;
    }

}


void Physics_StudyFrame::OnButton2Click2(wxCommandEvent& event)
{
    (StaticText2)->SetLabel(_("Second Click New Text"));
}
```



I dunno, In my head it seems that should work. But it just doesn't.

I thought about possibly making the button disappear on first click and then a new one re-appear, so that for the second click I could just use the new button. But... I don't even know where to begin for that one  :tongue2: 

Halp  :Sad:

----------


## Replicon

> ```
> void Physics_StudyFrame::OnButton2Click(wxCommandEvent& event)
> {
>     for (int a=0; a<2; a++)
>     {
>         (StaticText2)->SetLabel(_("FirstClick new Text"));
>         a = a + 1;
>     }
> 
> ...



I didn't look at any of your code, but this popped up immediately: why are you incrementing a twice? Once as part of the for loop (a++), and once at the end (a = a+1). while I have no idea what you're trying to do, I'd be shocked if this weren't seriously broken.

----------


## ninja9578

My guess is that you are using an event table for this, I would recommend connecting your events and disconnecting them manually.  

When you create it, do a ConnectEvent, on the first click, do a DisconnectEvent, then ConnectEvent to have it go to the new method.

----------


## slash112

> I didn't look at any of your code, but this popped up immediately: why are you incrementing a twice? Once as part of the for loop (a++), and once at the end (a = a+1). while I have no idea what you're trying to do, I'd be shocked if this weren't seriously broken.



A series of stupified attempts brought me to this equally stupid one.
Basically, I thought that I could use a loop, to make it sort of stop... or something. I dunno, it seems more stupid when I start thinking about it more...





> My guess is that you are using an event table for this, I would recommend connecting your events and disconnecting them manually.  
> 
> When you create it, do a ConnectEvent, on the first click, do a DisconnectEvent, then ConnectEvent to have it go to the new method.



Ahh, well this makes sense, actually.
*Goes to Google*

----------


## ninja9578

Just you you know, you should never do something like



```
a = a + 1;
```


Way to complicated, that gets transformed into this:



```
mov [a], ax
addi ax, 1
push ax             ;put it into temp storage
pop ax              ;get it out of temp storage
mov ax, [a]
```


5 lines of assembly is way too much.

The C++ way of adding a value to itself is



```
a += 1;
```


Which gets assembled to




```
mov [a], ax
addi ax, 1
mov ax, [a]
```


Bypassing the temporary storage you get down to three processor commands.

The processor has specialized functions for adding and subtracting 1 though so to add one to a variable.




```
++a;
```


 will be assembled into this



```
mov [a], ax
inc ax         ;much faster than addi
mov ax, [a]
```




Realistically, the optimizer will do that for you, but it's better to do it explicitly.

----------


## slash112

Ahh, I never knew that.

And... You say it is "++a", I thought it was "a++"...

Well, whichever it is, I never used that because I was experimenting with different numbers.

----------


## spacechase0

I think that ++a; does it before, while a++; would do it after.

If that's right, then this:



```
int a = 0;
int b = ++a;
```


Would make a and b equal to 1, while having it after a would make b equal 0 and a equal 1;

----------


## ninja9578

Yes.  But behind the scenes, it's a little more complicated than that.




```
int a = 0;
int b = a++;
//b equals 0 here, while a = 1
```


Here's what actually happened.
a was created and initialized to zero
a was copied
a was incremented
b was created, then initialized to the copy




```
int a = 0;
int b = ++a;
//a and b both equal 1
```


a was created and initialized to 0
a was incremented
b was created and initialized to zero

The difference is that copy.  Copying takes time and in the case a few posts ago, a copy is not needed and just wastes ram and cpu power.  Optimizing software is all about removing extra steps.

----------


## slash112

Ohhhhhh, I seee.

----------


## spacechase0

I had no idea, I guess I need to learn more about optimization then.  :tongue2: 

Thanks for the information.

----------


## ninja9578

Yeah, it's good to learn some of that.  When learning a language, always ask why one technique is better than another.  Optimizers are specialists, there are very few of us, but we are in high demand.  I'm probably in the less than 1% of programmers who can optimize at an assembly level.

----------


## Replicon

Use ++a when you don't explicitly need the pre-saved value. People who put a++ in all their loops are a pet peeve of mine. It doesn't really matter in the integer case, but if you're writing some insane iterator that has to do real work with lots of data, it will make a difference.

----------


## ninja9578

Me too, I ever seen post-increments in loops for Firefox and other huge programs.

----------


## musicaljelly

When creating an array, is it possible to define all of its contents manually in one go? I know that in python, you can do 



```
mylist = [item1, item2, item3]
```


Can this be done in C++, or would I have to manually access each index, as in 



```
int mylist[3];
mylist[0] = item1;
mylist[1] = item2;
mylist[2] = item3;
```


Thanks!

----------


## khh

Yeah, that's possible



```
int yourlist = { item1, item2, item3 };
```

----------


## musicaljelly

Sweeeeet. No idea why I couldn't find that in the tutorials I was using.

Thanks!

----------


## khh

Ninja, do you know of any good assembly language tutorials? Know it's not a C/C++ question, but I figured you're the person to ask. See, I'll be learning it at the university next semester, so I'd like to get a jump on it. Being the most computer literate guy, I know some of my friends will ask me for help, so it'd be good to actually know some.

----------


## ninja9578

Yes, "The Art of Assembly" by Randall Hyde.  You should be able to find it on Amazon.

----------


## khh

Ok, thanks. I'll check it out.

----------


## Invader

I have a question about a piece of code that's supposed to convert a 32 bit number into its base 10 form. Each digit of the 32 bit number is represented as an array value:

N[0] = 0
N[1] = 1
N[2] = 0

..and so on to N[31]. I use 'if' to check each array value and add the base ten value of that digit onto variable 'temp' (that I use for something else earlier) to end up with the base10 number.

My puzzlement is due to the fact that the program only functions properly when the if statement uses negative logic, as below.




```
d=2147483648;
for(k=0; k<32; ++k){
	if(N[k]!=0){
		temp = temp + d;
	}
	d/=2;
}
```


If however I use *if(N[k]=1)* then the program treats every array value (binary digit) as if it's 1, and I end up with 4294967295, or 232-1. This isn't the first time I've had to use a negative statement in order to get it to work. Bear in mind I'm still "fresh out of the box" new to c++ and don't know very much.

----------


## ninja9578

if(N[k]=1) is not doing what you think it is  :wink2:   What your code is doing is assigning N[k] to 1, and then checking the result of that assignment (which is 1) hence, it's always true.

You want if(N[k]*==*1)

a = b;  //assignment
a == b; //comparison

----------


## ninja9578

Take a look for yourself  :smiley: 




```
#include <iostream>

int main(int, char **){
   int a = 5;
   int b;
   std::cout << b = a << std::endl;
}
```

----------


## Invader

Wow. That makes a good deal of sense now! Thanks ninja.  :smiley: 

Oh, and while I'm here, I don't suppose you'd know something about urls? What my lil' program did was convert an IP address (like google.com's 66.102.7.99) into four 8-bit binary numbers and then grouped them as a 32 bit number, and converted them back to base ten, which in this example's case would yield 1113982819. I can take that number and enter it as the url and it'll take me to google.com. When I try that for, say, dreamviews.com (IP 208.43.31.59) I get the number 3492486971. That number however returns a 400 error (bad request). I know zip about networking. Seems fascinating though that the numbers can be played with in ways the browser will still understand.

----------


## ninja9578

What are you doing to try an get those web pages?  A browser won't let you do that.  You using libcurl?

----------


## slash112

So yea, this is nowhere near finished or anything, I'm just using this so I can get the loop working.
It doesn't exit the loop when "done" is said on the first input, which is what I am trying to get to work.

By the way, the code is for a thing I'm doing which has a shitload of links which need to be wrapped in "page[x]="link";"
Just to make my life easier for it.

So uhhh, what on earth is wrong with it? I cannot figure it out.





```
#include <iostream>
#include <sstream>

using namespace std;

int main()
{


    string link0;
    string link1;
    string link2;

    string codepart0;
    string codepart1;
    string codepart2;


    cout << "Enter links" << endl;

while (link0 != "done")
{


    cin >> link0;
    codepart0 = "page[0]=\"" + link0 + "\"" + ";";

    cin >> link1;
    codepart1 = "page[1]=\"" + link1 + "\"" + ";";

    cin >> link2;
    codepart2 = "page[2]=\"" + link2 + "\"" + ";";
}

cout << codepart0 << "\n" << codepart1 << "\n" << codepart2 << endl;



    return 0;
}
```

----------


## DuB

It's not exiting the loop because it's checking for the "done" string before it ever retrieves the user input in the body of the loop.

In other words, at the point when it checks for "done" (i.e., just prior to entering the loop), link0 has been defined but nothing has been assigned to it yet because it hasn't reached cin. So it proceeds to run through the entire loop regardless of input received. It doesn't check for "done" again until after the loop restarts, i.e., after the 3rd cin.

A simple solution is to do the first _cin_ before entering the loop. That way it is checking a variable that has received an assignment before running through its normal course, giving it the chance to exit if it receives "done."

Does that make sense?

----------


## slash112

Ahhhhh, yea, that makes sense. Thanks.

There ain't much I can do about that, because of the way I need to do the thing as a whole.

Imma need to totally change my approach.

----------


## Invader

> What are you doing to try an get those web pages?  A browser won't let you do that.  You using libcurl?



I'm not using libcurl. I just ping the web address to get an IP and enter that manually into the program, which then converts a 32 bit number into base 10. 1113982819 will take you to google if you enter that into the url bar in Firefox, I assume it'd do the same thing in any browser.. Er, did I misunderstand the question?

----------


## ninja9578

Oh, well it doesn't do that in Safari.  Your conversion was correct though.

----------


## slayer

In C++, when should I use the void command?




```
#include <iostream>
#include <math.h>
using namespace std;

int increase(int num);
int decrease(int num);

int main()
{
    int n;
    cout << "Enter a number and press ENTER: ";
    cin >> n;
    cout << "Function returned: ";
    if (n <= 0)
    {
        increase(n);
    }
    else
    {
        decrease(n);
    }
    return 0;
}

int increase(int num)
{
    for (int n; n <= 0; n++)
    {
        cout << n << ", ";
    }
}

int decrease(int num)
{
    for (int n; n >= 0; n--)
    {
        cout << n << ", ";
    }
}
```


I'm learning functions right now it says in my book that using void won't return a value, however I'm a bit confused by this. When and where should I use the word void? If I change the functions to use void it doesn't change anything in the final result. Hope the question makes since.

Sorry if I didn't really explain what I'm doing here.

----------


## DuB

Defining a function as void means that the function doesn't return any variables. So while your "int increase(...)" function could theoretically return an integer, "void increase(...)" would not return anything. It is useful for lots of things, perhaps most commonly for accessing the properties of an object the Right Way. E.g., "Person.setName(Thomas)", where setName is a void function defined under the Person object, and its purpose is simply to set the Person's name variable to the argument received by the setName function--"Thomas" in this case.

Right now using void functions doesn't change anything in your program's output because your functions aren't set to return anything anyway. That is, you don't have any "return" statements. You could alternatively conclude the increase function, for example, with "return n" and then feed the function itself into cout during the main function (e.g., "cout << increase(num)" or something to that effect; my C++ syntax is very rusty so that may not be exactly correct) and it would display the n variable as returned by the increase function.

It's hard to explain thoroughly without giving example code, which I am too rusty to provide.  :tongue2:

----------

