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

## guitarboy

(I know you want to, ninja)
Well, teach me. I have a compiler and I have basic knowledge, but I'd like to know more before I decide to take courses.

----------


## Ynot

http://www.cprogramming.com/

----------


## slayer

int main()
{
     int a, b;
     int result;

     a = 5;
     b = 4;
     a = a + 1;
     result = a - b;

     cout <<result<<endl;
}

It might look really confusing at first, but when you actually sit down and read it slowly, it's pretty easy to understand.

In the code I provided, I'm saying that a = 5 and b = 2, then I'm taking a and adding 1 to it, then taking the new answer of a and subtracting it from b which would give me 2.

I just started learning yesterday :3

I'm using code::blocks for my C++ writing along with the www.cplusplus.com website.

----------


## guitarboy

Should I learn C or C++ first?

----------


## slayer

I'm learning C++ to learn how to make my own game engine. I don't really know anything about C.

----------


## Ynot

either, really
they're 80% the same
(C++ started out as an extension to C)

depends if you prefer procedural or object orientated programming

----------


## khh

Well, it depends on what you want to do with it. C++ is better for large projects, while C is best if you're writing time-critical applications. C would also be the logical choice if you want to make other things than computer programs, like if you want to program other integrated chips.
Many hold that you should always learn C first and then move on to C++, as C++ almost is a superset of C, but either way knowing one will help you with the other.

----------


## Ynot

> Many hold that you should always learn C first and then move on to C++



I disagree with that

There's certain things that are the "right way" in C, but the "wrong way" in C++ (and vice versa)
Arrays being the biggy

You may fall into the trap of using wrong methodologies in either language

----------


## ninja9578

> There's certain things that are the "right way" in C, but the "wrong way" in C++ (and vice versa)
> Arrays being the biggy



 ::wtf::   Arrays are exactly the same in C and C++.

He's right about the right and wrong ways being different in C and C++

Critical section in C



```
void CriticalMethod(void){
   pthread_mutex_lock(somelock);
   //some critical stuff
   if (boolean){
      pthread_mutex_unlock(somelock);  //have to unlock in every exit path
      return;
   }
   //more critical stuff
   pthread_mutex_unlock(somelock);
}
```


Critical section in C++



```
//Autolock.h
struct AutoLock{
   public:
      AutoLock(pthread_mutex_t * lock){
         pthread_mutex_lock(lock);
         mylock = lock;
      }
      ~AutoLock(void){
         pthread_mutex_unlock(mylock);
      }
   private:
      pthread_mutex_t mylock;
}
```





```
void CriticalMethod(void){
   AutoLock lock(somelock);  //will automatically unlock when it returns
   //some critical stuff
   if (boolean){
      return;
   }
   //More critical stuff
}
```



***********************


What exactly would you like to know guitarboy, honoured you came to me  ::D: 

I learned C first, then taught myself C++.  I would recommend just learning C++, most programming is done in C++, and it's a lot easier.  It's also a good thing to understand object oriented programming.

Here's some things to understand, in order
Primitive types: int, long, float, char
Scope
methods and functions
pass-by-reference vs pass-by-value
const
Pointers
Objects (classes and structs)
Constructors and destructors

Feel free to IM me about anything  ::D:

----------


## Ynot

> Arrays are exactly the same in C and C++.



I know they are the same
but they're hailed in C, and frowned upon in C++

From the man himself
http://www2.research.att.com/~bs/bs_faq2.html#arrays

----------


## ninja9578

Oh, okay, you meant that in C++ you're supposed to use STL containers  :tongue2:   We still use arrays for various things though.

----------


## slayer

Actually I have a question...

I'm learning C++ and right now I'm reading about ++ and --

The example it gives me is this...

Example 1:



```
B=3;
A=++B;
// A contains 4, B contains 4
```


Example 2:



```
B=3;
A=B++;
// A contains 3, B contains 4
```


I don't really understand the whole ++ and -- and how it affects the A and B variables. Can someone explain how it adds up?

Edit: Also, how does all this make up a video game engine?

----------


## Ynot

increment and decrement
(Ie. add one, or subtract one)
used all the time when looping and keeping count of things

a++ means "return the value of a, and then increment it"
++a means "increment a, then return the value"

subtle (but important) differences, however the differences between the pre & post incrementation are only important if you care about the value of a variable mid-operation




```
for (i = 0; i < max; i++)
{

}
```


and



```
for (i = 0; i < max; ++i)
{

}
```


are identical in operation
(because we do not care about the value of 'i' mid-operation

however,
say we are keeping a count of something that we later need to step back through in reverse




```
void increment_something(int var)
{
    old_var = var++;
}
```


here, we do care about the value of var mid-operation, therefore we store the "old value" of var and increment var

You can of course do this



```
void increment_something(int var)
{
    old_var = var;
    var++;
}
```


then we've split the operation into two
and now we no longer care about the return value of the increment

----------


## ninja9578

> ```
> for (i = 0; i < max; i++)
> {
> 
> }
> ```
> 
> 
> and
> ...



Almost correct.  In for loops you want to do the latter because in order to return, then increment, it has to keep a copy of it.  Not a problem with ints, but with objects it can.

++ and -- are weird to learn.

b = ++a; is like this:
a = a + 1;
b = a;

b = a++; is like this:
b = a;
a = a + 1;

 :smiley:

----------


## slayer

Err...you're using some things in there I haven't learned yet. So I think you just made it more confusing for me...

Edit: Ok that makes it a little easier to understand...

So would it be something like this for the 2nd part?

b = 1;
b = a++;

Would the result be: b = 1, a = 2? Because I already defined b to equal 1 and then a equals b which is 1, then I add a to a to get 2, right?

----------


## Ynot

follow a tutorial on C++
I've always liked this one
http://www.cprogramming.com/tutorial/lesson1.html

It'll take you through the basics, and slowly build up to more complex things

*edit*
Just realised you're not the OP.....

----------


## slayer

Lol no I'm not  :tongue2: 

But I'll make good use of this thread...

Also, I'm following this tutorial so far: http://cplusplus.com/doc/tutorial/operators/

edit: but again, how does all this make up a video game engine? Or any program?

----------


## ninja9578

Well, we break it up.  We break down the seemingly huge task of a full program and break it down into pieces which are more manageable.  We then code each part, sometimes sticking the together in one executable, but more commonly, we create a complex set of dynamic libraries.

A video game engine would probably be about a quarter of a million lines of C++ code, broken up into maybe 1000 different files.

----------


## slayer

Wow...quarter of a million...

Well I guess that adds up fast seeing how small lines of code are.

A Roxxor wants me to make a simple text based game. I'm not sure how I'm going to do this...

----------


## ninja9578

Well, Most of use consider lines of code as actually newline characters, including white space and comments.

What kind of game?

----------


## Ynot

hangman is always a good first game

pick a random word from file of possible words
let the user guess letters
print letters found, and underscores for not found
keep a count of num guesses

----------


## slayer

> What kind of game?



Just a simple text based game. Maybe something like, "You grab a gun. What do you do next? Respond: Shoot the enemy. The  enemy dies."

I'm not really sure if that's how it's going to be though...

I'm wanting to make my own game engine and A Roxxor said he would help me out. We're going to be working on a 2D side scrolling platformer. I have all the ideas in my head and some of it's written down.

I think he said he's going to be working on the level editor and I'll be learning C++ and helping Drawsher with working on the sprites for the characters.

----------


## ninja9578

Oh oh oh, I'm doing that too.  ::D:   I'm calling my game Mavio.  I've got the shell of it all done, I just need to fill in my code out with the functionality  :smiley:

----------


## Ynot

the way to plan out a programming project is to start with a large idea and break it down into lots of smaller segments
then break those segments down further, and so on

You should end up with tons of really simple operations that are a doddle to code




```
void player::take_damage(int damage)
{
    player.health -= damage;

    if (player.health < 0)
    {
        died();
    }
}
```

----------


## slayer

So far all I've learned how to do is this:
http://img503.imageshack.us/img503/2765/67539020.jpg
Which comes out to be this:
http://img99.imageshack.us/img99/6329/69704121.jpg

----------


## ninja9578

Good start, maybe the next thing you can learn is how to save your screenshots in pngs instead of jpgs  :tongue2: 

Ynot speaks the truth, a good design is paramount to success, every detail should be worked out before any code is written.  Here is the design for the side scroller that I've started, I'll probably write it this weekend:


*Spoiler* for _Top Down Design_: 






```
Mavio
    Engine
	   GUI
		  GLUT
	   User Input
		  GLUT keyboard callbacks
	   Graphics
		  OpenGL
		  World
			 Background
				Large Bitmap, scrolling at 10%
			 Immediate Background
				Various sprites (not collidable)
			 World Data
				Displayed as blocks
			 Sprites
				Displayed on top of blocks
			 Special effects
				Clouds
				Fog
	   Main Engine
		  Animation
			 Modulus on frame count
		  Sprites
			 Mobile Sprite
				Mavio (Controlled by player)
				    Player States - Polymorphic motion and display classes
					   Mavio
					   Super Mavio
					   Fireball Mavio
					   Tail Mavio
					   Swimming
				Enemy Sprites
				    Not active until first render
				    Mindless
					   One-way roaming, run off cliffs
						  Mushrooms
						  Turtles
						  Armoured Turtles
					   Two-way roaming, turn around at end of cliffs
						  Turtles
					   No Gravity
						  Fish
						  Squid
						  Bullets
						  Fireballs
				    Intelligent
					   Boss
					   Ghosts
					   Fish
				Powerups
				    1Up
				    Super Mushroom
				    Tail
				    Invincible Star
				    Gold Coin
				    Silver Coin
				    Level End Flag
				    Peach (Princess)
				Mavio's Weapon
				    Fireball
			 Stationary Sprites
				Enemies
				    Flowers
				Powerups
				    Fire Flower
				    Floating Coin
				Background (Not Collidable)
		  Blocks
			 Collidable
				Hidden Prize
				    Bricks
				    Hidden
				    Question Marks
				Breakable
				    Weak Ice
				    Bricks
				Regular
				    Ground
				    Ice
				    Lava
			 Non-collidable
				Cloud
			 Semi-Collidable
				Tube
				Vine
				Ground, but can jump up through and walk through
				Water
				
	   Motion
		  Speed
		  Direction
		  Handles Collision Detection
		  Return State
			 Success
			 Failure
				Collision?
				    Top / Bottom / Left / Right
				Injury
	   Map
		  Choose Level
		  Undirected Graph
		  Level State
			 Next node for up, down, left, right (can be null)
			 Already beaten
			 Position on map
		  Bitmap
	   Level 
		  Loaders
			 Block Loader (LiveJSON)
				Uses JSON to map a block to it's polymorphic class
			 Sprite Loader (LiveJSON)
				Uses JSON to map a sprite to it's polymorphic class
			 Level Loader (LiveJSON)
				Creates block and sprite templates
				Creates a 2D array of blocks
	   Game Save (JSON)
		  Map Levels beaten
		  Lives
		  Current Mavio State
		  Points		  
    Data (all JSON)
	   Level
		  Enumerated Blocks
		  Enumerated Sprites
		  Level
			 XSize
			 YSize
			 Background Image
			 Immediate Background Data
			 World Data
			 Special Effect Name
	   Block
		  Collidable?
		  Breakable?
		  Images (Array of images if animated)
		  Animation loop start
		  Animation loop end
	   Sprite
		  Collidable?
			 Pixel Perfect Collisions?
			 With other Sprites?
		  Images (Array of images if animated)
			 Animation loop start
			 Animation loop end
		  Enemy?
			 Mindless or Intelligent?
		  Powerup
			 Powerup Script
		  Mavio's weapon?
```

----------


## slayer

> Good start, maybe the next thing you can learn is how to save your screenshots in pngs instead of jpgs



A haw haw

Looks like you've got quite a bit of work to do there...

How do I get away from the command prompt though? Like I want my own window made.

Edit: Also, do I use C++ in other things like Aleggro or SDL?

----------


## guitarboy

Thanks guys.
I'm going to learn C++ first, then maybe C. Oh, Ninja, what compiler/text editor do you use? I'm using code::blocks, but I also have xcode though it's more confusing. Which do you suggest?(I'm asking you because I now you're an apple guy  :wink2: )

----------


## ninja9578

> A haw haw
> 
> Looks like you've got quite a bit of work to do there...
> 
> How do I get away from the command prompt though? Like I want my own window made.
> 
> Edit: Also, do I use C++ in other things like Aleggro or SDL?



Not really, because I've mapped it all out, I think it will be fairly easy, each of those components shouldn't take more than 50 lines of code.

C / C++ is platform independent, so it has no support for windows natively.  You have to use an external library.  This could be X11, GTK, Windows API, wxWidgets, Qt, or GLUT.  For games, GLUT is the easiest choice because it's an extension on OpenGL.  GLUT is also the easiest for a beginner because it's C based, therefore there is no complex C++ functionality like Templates and inheritance and stuff.

Allegro and SDL can both be used in C++, however, OpenGL has been the graphics standard for 15 years.





> Thanks guys.
> I'm going to learn C++ first, then maybe C. Oh, Ninja, what compiler/text editor do you use? I'm using code::blocks, but I also have xcode though it's more confusing. Which do you suggest?(I'm asking you because I now you're an apple guy )



I use Code::Blocks when I'm writing code on Windows or Linux, and XCode and Code::Blocks when writing code on OSX.  Code::Blocks is far simpler, however XCode is the most powerful IDE out there.  So what I do for big projects is I write small components in XCode and use all of XCode's debugging tools and such to make sure it's right, then put them together in Code::Blocks.

----------


## slayer

How exactly do I draw an image onto the screen?

And I found a tutorial for making a window. I'm not sure if it was just the tutorial, but there is a butt load of code involved for making something as simple as that. You'd think it'd be easier right?

----------


## Ynot

> How exactly do I draw an image onto the screen?



I'm not a graphics guy (I hardly ever program GUI apps)

but using ninja's sugesstion of GLUT
here's sample code from a Glut tutorial




```
#include <GL/glut.h>

void renderScene(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,0.0);
        glVertex3f(0.5,0.0,0.0);
        glVertex3f(0.0,0.5,0.0);
    glEnd();
    glFlush();
}

void main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(320,320);
    glutCreateWindow("3D Tech- GLUT Tutorial");
    glutDisplayFunc(renderScene);
    glutMainLoop();
}
```


This will open up a window, 320x320, with a triangle in it

----------


## slayer

*sigh*

I think I'll just go back to learning lines of text and numbers...

----------


## ninja9578

Don't be intimidated, it's really quite simple if you know what each command does.  Follow the path of the code, it always starts at main, and I've put comments around the OpenGL and GLUT stuff explaining what each function does.  :smiley: 




```
#include <GLUT/glut.h>

void renderScene(void) {
    /*
	   glClear erases what's already stored in the drawing area,
	   GL_COLOR_BUFFER_BIT is the colour to restore it too, by default, it's black
    */
    glClear(GL_COLOR_BUFFER_BIT);
    
    /*
	   We want to draw a triangle, so tell OpenGL that the next drawing functions that we are doing
	   should be done in triangle mode
    */
    glBegin(GL_TRIANGLES);
	   /*
		  These are the verticies of the triangles, now with the default setup on the window, the window is 1x1, so
		  the coordinates are in relation to that.
	   */
	   glVertex2f(-0.5,-0.5);
	   glVertex2f(0.5,0.0);
	   glVertex2f(0.0,0.5);
    //This tells OpenGL that I'm done placing my coordinates and that it can draw it
    glEnd();
    /*
	   This one is also pretty complicated, OpenGL buffers it's drawing commands for optimization purposes
	   this glFlush command tells OpenGL that there are no more commands to come, and that it can go ahead and
	   finish drawing whatever's still in the buffer
    */
    glFlush();
}

int main (int argc, char ** argv){
    /*
	   This line initialized GLUT, which is the window engine and the interface to OpenGL
	   Internally, it loads the libraries and sets everything up
    */
    glutInit(&argc, argv);
    
    /*
	   This sets the initial display mode for OpenGL
	   GLUT_SINGLE means that it's using a single drawing page, so everything that gets drawn goes directly onto the screen
		  games should be double buffered to elimiate flickering
	   GLUT_RGBA tells glut that the pixels will be rendered in Red, Green, Blue, Alpha order
    */
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
    
    //These should be obvious, they're setting the window's position
    glutInitWindowPosition(100,100);
    glutInitWindowSize(320,320);
    //Creates the actual window
    glutCreateWindow("3D Tech- GLUT Tutorial");
    
    /*
	   This is a little advanceds, this is registering what's known as a callback function.  GLUT basically needs to know what do it
	   if it's in a situation where it needs to draw.  This could be the intial render, or of another window is moved over it, or if
	   it's resized.  glutDisplayFunc is given the name of the method that glut should call when it needs to redraw
    */
    glutDisplayFunc(renderScene);
    /*
	   Start the main loop :)
    */
    glutMainLoop();
    return 0;
}
```

----------


## Replicon

> I'm learning C++ to learn how to make my own game engine. I don't really know anything about C.



If you're just getting started with C++, I recommend a few smaller (like, MUCH smaller) projects first.  :smiley:

----------


## Ynot

> If you're just getting started with C++, I recommend a few smaller (like, MUCH smaller) projects first.



Indeed,
first learn the language, then do something small and easy to get the hang of things




> hangman is always a good first game
> 
> pick a random word from file of possible words
> let the user guess letters
> print letters found, and underscores for not found
> keep a count of num guesses




You've just started on your journey as a bridge-builder
Your ultimate aim is this
http://secretperson.files.wordpress....n-bridge-l.jpg
but you've got to start off building a few of these first
http://www.freeimageslive.co.uk/file...46.preview.jpg

----------


## ninja9578

I agree, you saw my design right?  Mario is a fairly simple game, yet it's quite a lot of classes and functionality.  I could probably knock it out in a day, but I'm very experienced.

----------


## slayer

I guess I made my first game!

Simple if/else statement set up.




```
#include <iostream>
using namespace std;

int main()
{
    int a;

    cout << "Please enter the number 3: ";
    cin >> a;
    if ( a == 3)
    {
        cout << "You have entered the right number!";
    }
    else
    {
        cout << "You lost the game.";
    }
    return 0;
}
```


If you enter the number 3, you win! But if you don't, then you lose!

How would I set it up so it repeats the first line of code?

I want to set it up so that if the player enters the wrong number, then it goes to repeat the "Please enter the number 3" part. Or, if they get it wrong, then it asks for the player "Do you want to play again? Y/N" and if they enter Y then the whole thing repeats itself, or if they enter N, then the game exits.

----------


## ninja9578

You need a loop.  C++ has a number of loops, but the one that you want is the do/while loop  :smiley:   Basically it's saying do {this code} while (this is true)




```
#include <iostream>
using namespace std;

int main()
{
    int a;
    char cc;
    
    do {
	   cout << "Please enter the number 3: ";
	   cin >> a;
	   if ( a == 3)
	   {
		  cout << "You have entered the right number!";
		  return;
	   }
	   else
	   {
		  cout << "You lost the game." << endl << "Would you like to play again? Y/N";
		  cin >> cc;
	   }
    } while (cc != 'Y');
    return 0;
}
```

----------


## Ynot

```
#include <iostream>
using namespace std;

int main()
{
    int a;
    bool correct = false;
    char play_again;

    while ( ! correct )
    {
        cout << "Please enter the number 3: ";
        cin >> a;

        if ( a == 3)
        {
            correct = true;
            cout << "You have entered the right number!" << endl;
        }
        else
        {
            cout << "You lost the game." << endl;

            cout << "Play again? (y/n): ";
            cin >> play_again;

            if ( play_again != 'y' )
            {
                correct = true;
                cout << "Thanks for playing." << endl << "Goodbye!" << endl;
            }
        }
    }
    return 0;
}
```


although I'll leave you with this
The above is not very clear to read (it's all in one function)
your job (when you get far enough along with the language) is to clean this up with a much simpler program flow


*edit*
beaten to it

----------


## slayer

What does the "char" do?

----------


## Ynot

it's the character datatype
meaning it stores a single character

a sequence of character datatypes "strung" together is where the word "string" comes from

----------


## khh

Edit: Never mind. Note to self: Learn to see if there are more pages.

But yeah, I also support you doing some smaller projects first.

----------


## Seeker

Have you given any thought yet to C#?  

C is pretty much dead except for embedded solutions, C++ is still a great language and supports object oriented design, but with modern hardware, all but the most time critical tasks can be handled with C#.  You also have the ability to call C++ unmanaged code from within wrappers if you have a section that needs to execute at it's fastest.

My suggestion for a compiler is Visual Studio 2005 or 2008 (2003 is OK, but doesn't support the .NET 2.0 framework well).  I've been using the Microsoft Cxx compilers since they were introduced and really like it.  In fact I'm using VS2005 as we speak.

----------


## khh

> Have you given any thought yet to C#?



C# is generally just used for Windows exclusive applications, though, and they require the .NET network to run. It's harder to write cross-platform applications. It's not as elegant at making native applications, though you're saved from hunting for external libraries or writing system-call wrappers yourself.





> C is pretty much dead except for embedded solutions, C++ is still a great language and supports object oriented design, but with modern hardware, all but the most time critical tasks can be handled with C#.  You also have the ability to call C++ unmanaged code from within wrappers if you have a section that needs to execute at it's fastest.



I thought C was commonly used for time-critical operations still, such as graphics modules.





> My suggestion for a compiler is Visual Studio 2005 or 2008 (2003 is OK, but doesn't support the .NET 2.0 framework well).  I've been using the Microsoft Cxx compilers since they were introduced and really like it.  In fact I'm using VS2005 as we speak.



I do however agree that Visual Studio is an excellent set of coding tools. I use VS2008 professional myself (no, it's not pirated... but neither is it bought).

----------


## ninja9578

Even unsafe C# code doesn't run as quickly as C++.

It's also very heavily dependent on the Windows runtime libraries.  I think C# is an atrocious attempt at making C++ more like Java.  C and it's derivatives are not meant to be safe, they're meant to do exactly what you tell them to do.

----------


## slash112

Wow...
I think I'm going to attempt to start learning C++ again...

I gave up pretty darn quick last time. Mostly because I was trying to get code::blocks or something and it wasn't working... is code::blocks like a plugin to microsoft visual C++ or something?
In fact, talking of which, is microsoft visual C++ the right thing to use?

EDIT: Hold on... is code::blocks entirely seperate from windows visual?

----------


## Ynot

code::blocks has nothing to do with MS
It's a cross-platform IDE for C & C++

I wouldn't get too hung up on IDE's to start with
Just code in a decent text editor (eg. Vim) and compile on the CLI

----------


## slash112

Ah yea, I had a look around google just there.

And... hrm... by the way I see it, I would rather use code::blocks.

I don't want to have to end up changing what I use once/if I get better at it. Besides... code::blocks looks more appealing than vim, and less complicated looking.

----------


## ninja9578

Code::Blocks is great, it's what I use professionally on Windows and Linux.  And it does all the complicated linking crap for you.

----------


## slash112

Cool, I have downloaded and installed code::blocks. Then it asked me what compiler to use, so I used windows visual C++ since it was already on my computer from last time I tried all this stuff.

My problem now is that it won't build or something, I click build, then I click run, and it says I need to build it. I then tried "build and run" and it just kinda does nothing. Don't know what the fuck is wrong here.

----------


## slayer

```
#include <iostream>
using namespace std;

int main()
{
    int a;
    a = 0;

    if ( a < 10 )
    {
        do
        {
            cout << a << " Adding one." << endl;
            a++;

            if ( a == 10 )
            {
                cout << a << " is the right number!" << endl;
                return 0;
            }

        } while ( a < 10 );
    }
}
```


Got my loop set up so that if _a_ doesn't equal _10_, then it keeps adding to it until it does. Pretty neat stuff right there :3

----------


## slash112

Fixed my problem, thanks to A Roxxor  :wink2: 

Now time to learn that bastard of a language  :tongue2: 

Also, nice one slayer.

----------


## L815

Here's another version of what slayer posted:



```
#include <iostream>

using std::cout;
using std::endl;

int main (void) {

    int a = 0;

    while (a < 10) {
        a++;
    }
    cout << "Congrats, the variable <a> hit 10!" << endl;

    return 0;
}
```


Just to add some more to study :p

----------


## guitarboy

What's the difference between C++ and dev C++

----------


## ninja9578

> Cool, I have downloaded and installed code::blocks. Then it asked me what compiler to use, so I used windows visual C++ since it was already on my computer from last time I tried all this stuff.
> 
> My problem now is that it won't build or something, I click build, then I click run, and it says I need to build it. I then tried "build and run" and it just kinda does nothing. Don't know what the fuck is wrong here.



Tell it to use GCC instead, MinGW should be automatically installed with Code::Blocks, and it more standard.

----------


## ninja9578

> What's the difference between C++ and dev C++



Dev-C++ is a deprecated IDE, it's not a language or even a compiler.  It uses the GCC compiler.  The project was discontinued and merged with Code::Blocks.





> ```
> #include <iostream>
> using namespace std;
> 
> int main()
> {
>     int a;
>     a = 0;
> 
> ...



Cool  :smiley:   But you don't need that first if statement.  You just assigned a to 0, there is no reason to check if it's less than ten since you know it will be  :smiley:

----------


## khh

> Cool   But you don't need that first if statement.  You just assigned a to 0, there is no reason to check if it's less than ten since you know it will be



But it doesn't really matter if you do, though. It's only one extra comparison. The place you really want to use a do...while is where you need to run the data through at least one literation before you're even ready to test the condition (can't think of such a scenario of the top of my head, though).

Also, instead of writing



```
int a;
a = 0;
```


Why not just write



```
int a = 0;
```


Uses less space and is actually a bit faster.

----------


## guitarboy

```
#include <isostream>

using namespace std;

int main()
{
     int a, b, total;

     cout << "Enter two numbers here...;" << endl;

     cin >> a >> b;

     total= a + b;

     cout << "Sum equals;" <<Total << endl;

     system(PAUSE) ;

     return 0;
}
```


returns 7 errors fix it dreamviews!

----------


## Ynot

> returns 7 errors fix it dreamviews!






```
/*#include <isostream>

using namespace std;*/

int main()
{
/*     int a, b, total;

     cout << "Enter two numbers here...;" << endl;

     cin >> a >> b;

     total= a + b;

     cout << "Sum equals;" <<Total << endl;

     system(PAUSE) ;
*/
     return 0;
}
```

----------


## slash112

Emmmm... doesn't that basically the actual code with :




```
int main()
{
     return 0;
}
```


?

I'm guessing that is some sarcastic way of saying his program can't be fixed?

----------


## slash112

Ok, I fixed it. Suck it, Ynot  :tongue2: .




```
#include <iostream>
using namespace std;

int main()
{
     int a, b, Total;

     cout << "Enter two numbers here...;"

     ;cin >> a >> b;

     Total= a + b;

     cout << "Sum equals;" <<Total << endl;

     return 0;
}
```



I had no idea what I was doing, but it somehow worked  :smiley:

----------


## ninja9578

Yeah, C++ is case sensitive.

----------


## khh

> ```
> #include <isostream>
> ```



It's supposed to be <iostream>, not <isostream> (input/output stream)

Edit: The compiler will also output which lines and expressions were making the trouble. Compiling that you'd first get an error stating that <isostream> couldn't be included in the project, and the subsequent errors came because std::cout and std::cin wasn't defined (the <iostream> header defines these values so you can use them)

----------


## slash112

I don't understand what it wrong with this. It says "error: expected primary-expression before "else"" and also "error: expected ';' before else"

It is supposed to be that it calculates the radius or circumfrence of a circle if you input the circumfrence/radius.

Have I done something wrong with the if/else thing?




```
#include <iostream>
using namespace std;

#define PI 3

int main()
{

double r, d, circle, entered_number;

cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;

if (entered_number == 1)
cout<<"To find circumfrence of circle, please input radius"<<endl;
cin>>r;
circle = PI * r * 2;
cout<<"The circumfrence of the circle is "<<circle<<endl;

else if (entered_number == 2)
cout<<"To find radius of circle, please input circumfrence"<<endl;
cin>>circle;
r = circle/(PI*2);
d = r * 2;
cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;

    return 0;
}
```


EDIT: Fixed it, but there is something wrong somewhere in it, even though it runs... I'll need to find that.

EDIT2: found that problem too... a very obvious one  :tongue2:

----------


## khh

you've forgotten to group the code propperly. What you wrote is basically




```
#include <iostream>
using namespace std;

#define PI 3

int main()
{
double r, d, circle, entered_number;

cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;

if (entered_number == 1) {
cout<<"To find circumfrence of circle, please input radius"<<endl;
}
cin>>r;
circle = PI * r * 2;
cout<<"The circumfrence of the circle is "<<circle<<endl;
else if (entered_number == 2) {
cout<<"To find radius of circle, please input circumfrence"<<endl;
}
cin>>circle;
r = circle/(PI*2);
d = r * 2;
cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;
    return 0;
}
```


When you wanted




```
#include <iostream>
using namespace std;

#define PI 3

int main()
{

double r, d, circle, entered_number;

cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;

if (entered_number == 1) {
cout<<"To find circumfrence of circle, please input radius"<<endl;
cin>>r;
circle = PI * r * 2;
cout<<"The circumfrence of the circle is "<<circle<<endl;

} else if (entered_number == 2) {
cout<<"To find radius of circle, please input circumfrence"<<endl;
cin>>circle;
r = circle/(PI*2);
d = r * 2;
cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;
}
    return 0;
}
```


If you want more than one block of code after an if/else/for/while/whatever statement, you need to enclose it in brackets. Also, it's common to indent blocks so that the end result looks like this (but it's strictly optional, C/C++ ignores excess white space)



```
#include <iostream>
using namespace std;

#define PI 3

int main()
{
	double r, d, circle, entered_number;

	cout<<"Enter 1 to find circumference, or enter 2 to find radius/diameter"<<endl;

	if (entered_number == 1) {
		cout<<"To find circumfrence of circle, please input radius"<<endl;
		cin>>r;
		circle = PI * r * 2;
		cout<<"The circumfrence of the circle is "<<circle<<endl;
	} else if (entered_number == 2) {
		cout<<"To find radius of circle, please input circumfrence"<<endl;
		cin>>circle;
		r = circle/(PI*2);
		d = r * 2;
		cout<<"The radius of the circle is "<<r<<" and diameter is "<<d<<endl;
	}
	return 0;
}
```


Makes the code much cleaner, as you can see.

----------


## slash112

Yea, I had it all fixed up like that. And yea, all my indents went away while editing it so much, deleting, adding in stuff, I ended up deleting all the indents. :tongue2: 

I could make the program much better than that, but right now, I'm just using it as a learning thing. Next thing to try is to use the loop thingy (do while?), so that the program stays open and you can calculate more.

----------


## ninja9578

You should also loop into while loops and for loops.




```
int a = 50;
do{
   std::cout << "I'm inside the loop " << a++ << std::endl;
} while (a < 10);
```





```
int a = 50;
while (a < 10){
   std::cout << "I'm inside the loop " << a++ << std::endl;
}
```


Have one but very important difference, see if you can figure out what it is  :smiley:

----------


## slash112

Well, one of them is a while loop, and one is a do while loop. I don't really understand the difference, even after reading about it.

I should look at this page on loops for ages. I have trouble taking in/reading that much information at once, mainly because of a short attention span. I'll just have to try...

----------


## guitarboy

Thanks, slash.
How do I run it in a window instead of terminal?

----------


## slash112

Yea... I was wondering the same thing.

I want to learn how to make a GUI. It isn't necessary at this stage though, anyway.

----------


## ninja9578

> You should also loop into while loops and for loops.
> 
> 
> 
> 
> ```
> int a = 50;
> do{
>    std::cout << "I'm inside the loop " << a++ << std::endl;
> ...



The difference has to do with where the check is made.  In the first bit of code, the check doesn't happen until after what's inside the loop has been done, therefore, it ALWAYs gets done at least once, the second piece of code does the check beforehand, so it may never get called  :smiley: 

Stick with terminals for now, I'll show you how to make a window a little later.  :smiley:

----------


## guitarboy

alright, I wrote a program that gives you the circumference of a circle after you put in the circumference and the approximate of pi.
How can I make it simpler, i.e; tell it that the variable p is 3.14, without you having to put it in.



```
#include <iostream>
using namespace std;

int main()
{
     int r, p, Total;

     cout << "Enter radius and pi approximate here... "

     ;cin >> r >> p;

     Total= r * r * p;

     cout << "Circumference is " <<Total << endl;

     return 0;
}
```


and how do I run it in a window, not terminal

----------


## ninja9578

> alright, I wrote a program that gives you the circumference of a circle after you put in the circumference and the approximate of pi.
> How can I make it simpler, i.e; tell it that the variable p is 3.14, without you having to put it in.
> 
> and how do I run it in a window, not terminal






```
#include <iostream>
using namespace std;

#define PI 3.141592654357

int main()
{
     float r, Total;

     cout << "Enter radius here... "

     cin >> r;

     Total= r * 2 * PI;

     cout << "Circumference is " <<Total << endl;

     return 0;
}
```


First off, ints are just integers, you need decimals for this, so we use float instead.  Also, your formula was wrong  :tongue2:  Circumfrance = pi time diameter, you were calculating area. lol.

#define is what's called a macro, it's not real code.  When the compiler compiles your source code, the first thing that it does, it copies and pastes macros.  So when the code gets compiled, the literal value of pi gets replaced at all occurrences of PI.  It is standard practice to keep definitions in caps, although not necessary.  :smiley:

----------


## slash112

Nice, guitarboy. It's funny how different I would do it from that. It's amazing the amount of possibilities for one single purpose.

Also, you don't really need a window yet, do you.

----------


## guitarboy

> ```
> #include <iostream>
> using namespace std;
> 
> #define PI 3.141592654357
> 
> int main()
> {
>      float r, Total;
> ...




radius * radius= diameter, times pi  :tongue2: 





> #define is what's called a macro, it's not real code.  When the compiler compiles your source code, the first thing that it does, it copies and pastes macros.  So when the code gets compiled, the literal value of pi gets replaced at all occurrences of PI.  It is standard practice to keep definitions in caps, although not necessary.







> Also, you don't really need a window yet, do you.



it would be nice to know how to do it.
And color it.
and change text color.
etc. 
 :smiley:

----------


## Ynot

> radius * radius= diameter



plus, not times

----------


## guitarboy

> plus, not times



ohfail 
:O
time to review 5th grade math  :Sad:

----------


## slash112

Lolfail  :tongue2: 

I had it in my program. I had defined PI to be 3 because I was lazy, I never did it exact because it was only for testing purposes. But yea, formula was: cirumfrence = PI * r * 2 and for radius I had r = circumference/(r*2).

All I did was let the "user" input the circumference if they wanted radius, or input radius if they wanted circumference.

----------


## Ynot

> Also, you don't really need a window yet, do you.
> 			
> 		
> 
> 
> it would be nice to know how to do it.
> And color it.
> and change text color.
> etc.



I understand why you want to get into GUI stuff, but trust me, at this stage it'd just confuse you

You've got to get a proper handle (no pun intended) on the language before delving into external APIs

At present, you're doing really simple maths with C++
you've yet to grasp the more advanced concepts needed for GUI apps

We haven't even covered stuff outside main() yet
let alone classes, templates, memory allocation, STL, etc. etc.

Walk, then run
But right now, we're still bobing about in the sea, before we developed legs

----------


## ninja9578

> You've got to get a proper handle (no pun intended)



 ::lol::  I get it  ::D: 

Now lets do methods, this program how two methods, one for area, and one for circumference, and the user gets to decide which to use.




```
#include <iostream>
#define PI 3.14159

float Circumference(float r){
   return r * 2 * PI;
}

float Area(float r){
   return r * r * PI;
}

int main(){
   //Get the radius of the circle from the user
   float radius;
   std::cout << "Enter radius." << std::endl;
   std::cin >> radius;

   //Get the function wanted
   std::cout << "\nPress 1 to Calculate Circumference.\nPress 2 to Calculate Area" << std::endl;
   int option;
   switch (option){  //kind of like a fast if / else
      case 1: //do if option == 1
         std::cout << Circumference(radius) << std::endl;
         break;
      case 2: //do if option == 2
         std::cout << Area(radius) << std::endl;
         break;
      default:  //neither of the other options
         std::cout << "Error, you didn't input one or two" << std::endl;
   }
   return 0;
}
```

----------


## guitarboy

Alright.
Whhat should I learn next, then? Youtube lessons are not my friend.

----------


## guitarboy

what is the std::--- for?  
Why not just cout, int etc.

----------


## ninja9578

Hmm... how to describe how namespaces work  ::?:   That's not important right now (and an odd concept before learning classes,) you can use cout simply and add a using namespace std at the top of the program.


Basically, there are multiple couts and the compiler has to know which one to use.  std:: tells it to use the std one, you did that in your program by defining that the entire program uses std.  Here's a little demonstration of namespaces.




```
#include <iostream>
using namespace std;

namespace Integer{
  int var = 5;
}

namespace Decimal{
  double var = 3.1416;
}

int main () {
  cout << Integer::var << endl;
  cout << Decimal::var << endl;
  return 0;
}
```


Weird, I know, but very useful for more advanced programming, for now you can forget what I just said  :tongue2:

----------


## guitarboy

> Hmm... how to describe how namespaces work   That's not important right now (and an odd concept before learning classes,) you can use cout simply and add a using namespace std at the top of the program.
> 
> 
> Basically, there are multiple couts and the compiler has to know which one to use.  std:: tells it to use the std one, you did that in your program by defining that the entire program uses std.  Here's a little demonstration of namespaces.
> 
> 
> 
> 
> ```
> ...



You said something?
I'll come back to it.  :smiley: 

Alright, a few questions-

float Circumference(float r){
   return r * 2 * PI;
}

float Area(float r){
   return r * r * PI;

What's that for? 
and why do you have to put \n

----------


## guitarboy

Why isn't this working? It says I need } at the end, but I did...



```
#include <iostream>

using namespace std;

int main ()

{
    int x = 3;
    int y = 4;

    if (x > y)

    {
        cout << "X is greater then Y " << endl;
    }
    else
        {cout << "X is less then Y " << endl;

    system("PAUSE");
    return 0;
}
```

----------


## ninja9578

> You said something?
> I'll come back to it. 
> 
> Alright, a few questions-
> 
> float Circumference(float r){
>    return r * 2 * PI;
> }
> 
> ...



Those are methods.  That's how you do things multiple times, you can keep calling that as many times as you want.  Everything is done like this, even << in cout is kind of a method.

\n is just a newline character, it's the same as endl, but can go inside of the quotes, I just did it to save space.





> Why isn't this working? It says I need } at the end, but I did...
> 
> 
> 
> ```
> #include <iostream>
> 
> using namespace std;
> 
> ...



You have a stray bracket before the last cout, you never close it.  :smiley:

----------


## Ynot

> Hmm... how to describe how namespaces work   That's not important right now



Well, namspaces do use the same delimiting syntax as class methods, so I think an understanding is helpful

*Namespaces*




```
#include <iostream>
using namespace std;

int main()
{
    cout << "hello world" << endl;
    return 0;
}
```


Note the #include line,
we're pulling in external code
specifically, code to allow input / output of data using streams

There's loads of external code you can pull into your program to acheive common tasks
because of this, it's important to separate code into "namespaces"

Say we are making a program that tracks finances of a company
We could define a couple of classes in our program to track money incoming and outgoing from our company
We may call these classes "cin" for cash in, and "cout" for cash out
but we'd have a problem - these names clash with the names defined in iostream for input & output to the standard streams

For this reason, any "standard" external code (Ie. comes with all compilers and is expected to be present) is separated off into it's own namespace, called "std"

This brings us to the second line
using namespace std;
is asking the compiler, should it come across something not defined in our program's namespace, to look in the standard namespace for it

You can omit the "using namespace std" line, and append the std namespace to object calls
The above can be re-written to this



```
#include <iostream>

/*
 * we don't need this line anymore
 * as we're using absolute referencing
 * for std objects
 */
// using namespace std;

int main()
{
    std::cout << "hello world" << std::endl;
    return 0;
}
```


So, namespaces
just a way to separate out definitions so code from different sources don't clash with each other

----------


## khh

> Now lets do methods, this program how two methods, one for area, and one for circumference, and the user gets to decide which to use.



Those are functions. I thought you only used the term "methods" for member functions of classes.





> \n is just a newline character, it's the same as endl, but can go inside of the quotes, I just did it to save space.



Except that endl also flushes the stream  :tongue2:

----------


## Replicon

> Except that endl also flushes the stream



I'm pretty sure new line also ends up flushing the stream. This might be implementation-dependent though. Not sure what the actual spec says.

----------


## Ynot

\n doesn't flush the stream
\n is just a character, and therefore cannot "do" anything

----------


## ninja9578

Ynot's right, \n does not flush the stream.

This is why \n is useful for inside of a string, it allows you to keep buffering it instead of having to wait for the buffer to be flushed.

----------


## Replicon

Well, SOMETHING is flushing the stream, because when I run:




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

int main(void)
{
    cout << "Thingger1\n";
    sleep(1);
    cout << "Thingger2" << endl;
    return 0;
}
```


I get "Thingger1" displaying immediately, then it pauses for a second, and then Thingger2 displays. This has consistently been my experience for years and years. If it didn't flush the stream, it would have paused a second and then displayed both lines at the same time. So, what's happening here if not flushing? It might be the lower level stream operations that happen under the hood, but you can't deny this behaviour.  :smiley: 

EDIT to add: Did some googling, and it seems that this is dependent on the compiler. I suspect cout is special in that behaviour, and other streams (fstream, etc.) don't do that. Back in the C days, it was the same story with '\n' and printf.

----------


## ninja9578

\n isn't flushing the stream, in most compilers, the stdout streams aren't buffered because there is boatloads of memory and speed to burn.  But you're not guaranteed to get that result all the time.  Try it with file i/o and see what you get  :tongue2:  

Just remember there is a difference between what a compiler will do and what the C++ Standard states.

Case and point:



```
if ((sizeof(char) < sizeof(short)) &&
             (sizeof(short) < sizeof(int)) &&
             (sizeof(int) < sizeof(long))){
   cout << "Expected" << endl;
}  else {
   cout << "Reality on most compilers" << endl;
}
```


The C++ Standard states that sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long), but it's perfectly legal for them to even be the same size.

----------


## slash112

I have a question.

In this program, when you input two words, (i.e. first name and second name) it only takes the first word. I read somewhere in the tutorials of a data type that takes in any amount of words, rather than one. But I can't seem to find it. In fact, I'm not even sure if it was to do with data types or not.

But anyways, yea, how would I allow for two words to be input?




```
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string question = "What is your name? ";
    string greeting = "Hello, ";
    string yourname;

    cout << question << endl;
    cin >> yourname;
    cout << greeting << yourname << endl;

    system ("PAUSE");
    return 0;
}
```

----------


## Ynot

standard streams are whitespace delimited (unix convention)
use getline() to get an entire line (up to newline char)




```
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string question = "What is your name? ";
    string greeting = "Hello, ";
    string yourname;

    cout << question << endl;
    getline(cin, yourname);
    cout << greeting << yourname << endl;

    system ("PAUSE");
    return 0;
}
```


btw, what's this system("PAUSE") thing?

----------


## slash112

Oohhhhhhhh... Thanks.

system("PAUSE") means that when I run the program, it doesn't close as soon as it finishes. But it lets you close it by pressing any key.
Within the programing software stuff it isn't an issue, but when it is the .exe on it's own, when you run it, it would close the moment you finish inputing stuff.

----------


## ninja9578

Code::Blocks automatically pauses the execution at the end for you, you don't need that unless compiling or running outside of the IDE  :smiley:

----------


## slayer

How to I package together my code into an exe or something both windows and macs can open?

----------


## slash112

> Code::Blocks automatically pauses the execution at the end for you, you don't need that unless compiling or running outside of the IDE



Yea, which is why I like to add the system ("PAUSE") at the end all the time. Not that it is important when I am just making stupid little things, but I just like to do it anyway.

----------


## ninja9578

> How to I package together my code into an exe or something both windows and macs can open?



A dos console and unix consoles are completely different. Macs can run windows console programs, you need to compile seperately for mac and windows

----------


## slayer

> A dos console and unix consoles are completely different. Macs can run windows console programs, you need to compile seperately for mac and windows



Then how do I do it just for windows?

----------


## Ynot

> system("PAUSE") means that when I run the program, it doesn't close as soon as it finishes. But it lets you close it by pressing any key.



Don't do that
I'm not sure exactly what you mean by "closing" (you mean the terminal window?)
but good programs finish as soon as they're done, and do not hang for user input unnecessarily

Say you release a program that takes input from stdin does something and outputs to stdout, exiting 0 on success and any other value on error, errors get sent to stderr

I would like to be able to say something like




```
slash112_program || echo "Error $?"
```


or


```
cat some_file | slash112_program | less
```


hanging the program for input at the end breaks program flow
anyway....





> How to I package together my code into an exe or something both windows and macs can open?



You can't (well, you can, but it's way more trouble than it's worth)
Either make the various platform & architecture packages yourself
or the easy route - just release the code
If the program's useful, people will package it up for their platform / architecture of choice

----------


## ninja9578

> Then how do I do it just for windows?



It does that for you  :smiley: 

Go to the folder with your Code::Blocks file, then go to bin/Debug.  A .exe file should be in there  :smiley: 

If you use standard C++, it will compile on any platform with no change in code  ::D:   Firefox compiles on every major platform, using the same code, with very little preprocessor.

----------


## The Invisible Man

"C++ will let you shoot your foot without warning you. In fact, it will even load the gun for you." 

~ Allegro User

----------


## slash112

Ynot. I'll give you an example. If the program asks you to input something, you would put it in. You would get an instant response, and then the terminal window would instantly shut the moment after the new text is displayed. This is not what you want.

It's not that I need it at this level, I don't need any fancy way of closing the program at this level. It is just purely for having it there.

----------


## khh

> If you use standard C++, it will compile on any platform with no change in code   Firefox compiles on every major platform, using the same code, with very little preprocessor.



There are a lot of things you need system calls for, though, like GUI and scanning directories and such. So Firefox must be using preprocessor directives, or libraries which uses them.





> Ynot. I'll give you an example. If the program asks you to input something, you would put it in. You would get an instant response, and then the terminal window would instantly shut the moment after the new text is displayed. This is not what you want.



Console programs are normally opened from the terminal, though. And if you do that, then the terminal doesn't close and you'll see the output. It's just if you open it by double clicking on the executable that you won't see the text, but then that's no how the programs are supposed to work. If you want those kinds of programs you need GUI.

Funny thing, I've got C++ as a university subject this year. Of the things we'll learn this year, there was only one thing I haven't done before.

----------


## ninja9578

> There are a lot of things you need system calls for, though, like GUI and scanning directories and such. So Firefox must be using preprocessor directives, or libraries which uses them.



I said little preprocessor.  I've looked at the Firefox code because I reverse engineered a chunk of it.  All of this stuff uses a NPWindow object, almost all of the preprocessor is in there.





> Console programs are normally opened from the terminal, though. And if you do that, then the terminal doesn't close and you'll see the output. It's just if you open it by double clicking on the executable that you won't see the text, but then that's no how the programs are supposed to work. If you want those kinds of programs you need GUI.



But stick with the terminal while learning, GUIs can be a pain.





> Funny thing, I've got C++ as a university subject this year. Of the things we'll learn this year, there was only one thing I haven't done before.



But I'm sure that you'll learn better technique and optimization techniques that you currently don't know.  :smiley:   Assuming the professor is competent, I had a professor in college who was a good C++ programmer in 1995, but he stuck to those techniques, so we were taught no modern designs.  C++ coding changes very quickly, if you don't stay on top of it, you can fall behind quickly.

----------


## slash112

I can't wait till I get to GUIs. That will be kick ass.

----------


## ninja9578

C++ is a nightmare with GUIs because the language isn't designed for it.  I just spent 3 full workdays creating a frame, a dynamic set of menus, a status bar, and a web preferences pane.  :Sad: 

Luckily, there are graphical ways to do it in 5 minutes, which is what I recommend using when starting out.  The only reason I don't use that is because I need more control over them.

----------


## slash112

Haha, wow.

But still... it would be worth it.

I applied to a computer games course which consists of programming in C++ (I think...) and 3d modelling. I want to get into that (although I applied to physics too, at the time I wanted that more)

But yea... I'm just learning this so I have a bit of knowledge before going there (If I get in)

----------


## khh

> I said little preprocessor.  I've looked at the Firefox code because I reverse engineered a chunk of it.  All of this stuff uses a NPWindow object, almost all of the preprocessor is in there.



Ah, okai.





> But stick with the terminal while learning, GUIs can be a pain.



Yeah, I know. I tried learning GUI a while back, but I simply gave up on it for a while. I didn't have a clue about what I was doing, or what the code elements meant or anything. Figured I'd just write a console program with some of the same functionality and port it when I was ready :p






> But I'm sure that you'll learn better technique and optimization techniques that you currently don't know.   Assuming the professor is competent, I had a professor in college who was a good C++ programmer in 1995, but he stuck to those techniques, so we were taught no modern designs.  C++ coding changes very quickly, if you don't stay on top of it, you can fall behind quickly.



Yeah, I hope so. There must be things I've missed, since I've mostly thought myself what I know. But I think he must be a good programmer, he's taught that specific course for the two year it's run, and he taught the Java course the engineers attended instead. He ought to be good by now.

----------


## ninja9578

Good Java Programmer != Good C++ Programmer, very different designs.

Also, almost all of your functionality can be done using the console.  I'm currently tearing apart an application so that the functionality is completely disjoint for the main window.  The window runs by itself and loads the functionality as a dll.

----------


## khh

> Good Java Programmer != Good C++ Programmer, very different designs.



Yeah, I'm aware of that, but he's an experienced programmer, he's used quite a few different languages, so I'm guessing he'd want to teach the language properly. Also, he started introducing "best practise" rules the second lesson (accurate ones). That's a good sign.

----------


## ninja9578

If you have Ubuntu, I'll show you how to create a simple GUI program if you want.  I can do it on Windows too, but I like using the wxWidgets library for that, and that's impossible to compile on Windows, I've tried and failed at that many times.  I'm not looking forward to the next major release because I'm planning on recompiling it as a dynamic library.

----------


## khh

> If you have Ubuntu, I'll show you how to create a simple GUI program if you want.  I can do it on Windows too, but I like using the wxWidgets library for that, and that's impossible to compile on Windows, I've tried and failed at that many times.  I'm not looking forward to the next major release because I'm planning on recompiling it as a dynamic library.



Yeah, that would be nice. I've got Windows and Ubuntu as dual boot. Me and a friend once thought about making an application with wxWidgets, but... we never quite got there.

----------


## Sornaensis

wxWidgets works perfectly fine on Windows Vista... Code::Blocks with wxSmith does a lot of the work, but it's perfectly possible to code everything by hand with a wx Template.

----------


## ninja9578

Then you're lucky.  wxWidgets is a very complex build, and it requires a lot of external libraries which do not come with the source.  It's really annoying to build.

----------


## Sornaensis

If I'm not mistaken all I had to do was download the source [I think there is a windows version or something...?] and then tell code::blocks where it was and it compiled it for me. Now all I have to do it fire up a template or use wxSmith ^_____

----------


## ninja9578

Here's a list of things to learn before tackling GUIs

methods
header / functional files
classes / structs
static vs dynamic methods
overloading methods
overloading operators
scope
pass by reference vs pass by value
polymorphism / inheritance
inline functions
macros
pointers
reference / dereference
casting
opaque pointers
callback functions
static libraries vs dynamic libraries
preprocessor

If you know those, then you know .01% of C++  :smiley:

----------


## Ynot

the other 99.99% is divided evenly between exceptions and trying to understand the Boost libraries.....

----------


## ninja9578

And STL  :tongue2:

----------


## SkA_DaRk_Che

Hey Ninja, i dont know too much about programing and that type of stuff so 1  basic and dumb q.

What kind of applications do you most commonly use programming for? What possible uses does it have?

----------


## Ynot

every action, every task
everything that is possible on a computer
starts out life as source code written in a programming language





> What kind of applications do you most commonly use programming for?



all of them



> What possible uses does it have?



everything

----------


## ninja9578

I think Soros was asking me specifically  :tongue2: 

I professionally write a variety of programs that revolve around our custom GUI format.  It's basically a GUI engine, coupled with our database that allows us to build very complex gui apps and websites, really fast.  I write the backend engine that runs the thing and communicates with the server.

I also write games from time to time if I'm practicing a new technique or something.

----------


## slash112

I was just wondering. How would you make it so that you just press a key and it would do something. For example:

if spacebar is pressed
cout << "OMG you pressed space!"


How would you code that first line? And would you need to set a variable for it?

Same with any key, like the left arrow key, or whatever. Just something where you press the key without having to hit enter too.

----------


## ninja9578

Well if you're using glut, you can register a callback for that.  Otherwise, you have to have a loop that continually check for it.




```
#include <pthread.h>
pthread_t keyboard_thread;
void * keyboard(void * argument){
   char mychar = '\0';
   while(mychar != 'x'){  loop until an x is pressed
      fflush(stdin);
      scanf("%c",&mychar); 
      switch (mychar){
         case ' ':
            cout << "Space bar pressed" << endl;
            break;
      }
   }
   return 0;
}

int main(){
   pthread_create(keyboard_thread, NULL, keyboard, NULL);

   //Do whatever you want

   return 0;
}
```


 ::D: 

That's threading though, which is a little more complicated.

----------


## khh

That'll only get input characters, though, like space and a, b, c, (...). The arrow keys and enter and all of those won't be registered, right? Also, pthreads doesn't work on windows.

----------


## ninja9578

pthreads works on windows  :tongue2:   I use it all the time.

And yeah, then you use glut or another library with keyboard callbacks built in like wxWidgets or Qt or the Windows API  :tongue2:

----------


## Ynot

intercepting keystrokes is non-trivial
as it's highly dependent on the environment (including whether the input stream is buffered or not)

Best bet is to use a curses library
(that's what all the text adventure games use)
http://en.wikipedia.org/wiki/Curses_...ing_library%29

----------


## slash112

Jesus shitter, it sure is complicated for such a simple thing.

----------


## Ynot

Well, intercepting keystrokes straight off the device isn't simple
The OS has hooks to the keyboard device, and you're overriding them

But the complexity of many things boils down to the desire to remain platform & architecture neutral

I'm sure there's a simpler Windows specific hook you could tap into to intercept keyboard characters, but then you're hamstrung to a specific platform
(and at the mercy of the platform to maintain the hook across future versions of the OS)

----------


## ninja9578

Hooks are abstracted, Windows can change them and the APIs should still all work fine.  Oh, abstraction is something that should be added to that list that I made.

----------


## Alric

I have taken a bunch of different programing classes, and really the key is getting into the right frame of mind. Once you know one program its a lot easier to learn most others. Even entirely different programs use the same basic concepts.

----------


## ninja9578

I find that's true only if it's in the same paradigm.  Knowing a procedural language it hard to go into a OOP language, and an assembly language is really weird.  :tongue2:

----------


## Alric

That is probably true. The ones I have worked with is java and c++ which are very alike. And the oracle programing language which is used for databases and stuff, I forget what it is called but its a lot like them too. As is HTML, which is like an entirely different area making webpages and stuff, but interactive websites uses a very similiar method.

Also the small programs you download for like games and stuff. A lot of time they got their own languages for using inside the game(like games that lets you make maps and stuff). A lot of time they are based off this same type of stuff.

There can be big changes at time. But once you learn one it defenitly helps you with learning all the related ones.

----------


## khh

> I find that's true only if it's in the same paradigm.  Knowing a procedural language it hard to go into a OOP language, and an assembly language is really weird.



I don't know about that. I first learned "programming" in PHP (which I reckon as a procedural language), which in turn helped me when I learned javascript (which is object oriented).

----------


## ninja9578

Just js is a very very simple object oriented language.  java and C++ are insanely complex and powerful.

khh, you are refering to scripting languages, I've written 5 of them myself for various reasons.  Yeah, those can be weird sometimes.

----------


## khh

> Just js is a very very simple object oriented language.  java and C++ are insanely complex and powerful.



Yeah, I know but the stuff you learn is transferable :p





> khh, you are refering to scripting languages, I've written 5 of them myself for various reasons.  Yeah, those can be weird sometimes.



Aye, that's why I wrote "programming" in quotation marks.
But did you really write 5 complete scripting languages? Why on earth would you need five of them?

----------


## Ynot

php has had a full object model since v5 (2004)
http://uk3.php.net/manual/en/oop5.intro.php

----------


## ninja9578

Gemini BASIC - A very simple calculator BASIC language for a GUI that I wrote for a Dev Engine
Cardinal BASIC - A more advanced BASIC language for Gemini's replacement
Inspiration Script - A scripting language for a game engine that I never released  :Sad: 
Mini MIPS - For a class in college, based on MIPS Assembly
LiveScript - Scripting language for my company's engines, I also now use it for personal project





> php has had a full object model since v5 (2004)
> http://uk3.php.net/manual/en/oop5.intro.php



It's still very primitive when compared to java or C++.

----------


## Ynot

> It's still very primitive when compared to java or C++.



Oh absolutely,
I'm just saying though

(plus OOP somehow seems wrong with web development - I don't know it just doesn't feel right somehow)

----------


## khh

> (plus OOP somehow seems wrong with web development - I don't know it just doesn't feel right somehow)



But you can use php as a scripting language on your computer, though, like python or perl or whatever. It's actually surprisingly suited for it.





> Gemini BASIC - A very simple calculator BASIC language for a GUI that I wrote for a Dev Engine
> Cardinal BASIC - A more advanced BASIC language for Gemini's replacement
> Inspiration Script - A scripting language for a game engine that I never released 
> Mini MIPS - For a class in college, based on MIPS Assembly
> LiveScript - Scripting language for my company's engines, I also now use it for personal project



Why so many BASIC languages? And why did you have to invent your own language each time? For some of the projects, like the game engine, wouldn't it be better to just implement LUA or something?

----------


## ninja9578

> Oh absolutely,
> I'm just saying though
> 
> (plus OOP somehow seems wrong with web development - I don't know it just doesn't feel right somehow)



Not really, the DOM is object based  ::?: 





> But you can use php as a scripting language on your computer, though, like python or perl or whatever. It's actually surprisingly suited for it.
> 
> 
> Why so many BASIC languages? And why did you have to invent your own language each time? For some of the projects, like the game engine, wouldn't it be better to just implement LUA or something?



Because the first two were a long time ago when I didn't have understanding of how compilers worked.

And LiveScript is designed for graphic designers to understand, so it has to be simple and not be too "programming languagy," which python and perl are.

----------


## slash112

Does all this shit become more clear when taught by someone in university?

I fucking hope so... or else I applied to the wrong dam course.

----------


## ninja9578

It depends on the teacher.  Some of the teachers learned C++ 15 years ago and never bothered learning the new stuff.  

And yes, when you're immersed in it, it will make much more sense.  C++ is a weird language compared to some of the other ones.

----------


## slash112

Oh cool. I certainly hope it will make more sense (if I get accepted), the course looks extremely good. (Includes other things too)

----------


## Alric

The more advanced a programming language is, the easy it is to program with it. Basically, the makers of the program already did a lot of the work for you.

However advanced programs with a lot of prebuilt commands in it, has more data that has to be read. If your not actually using all the prebuilt commands and stuff, there is wasted code, and thus the final program will run slower than if the commands weren't there.

The reason there are so many languages, is because people have difference needs. Normally its based around time. Either the time it takes to code, or how fast it will run.

If you were making a basic calculator, then speed probably isn't an issue. You would use a language with all the math commands built in already, because its silly to reinvent that code. In this case, your personal time is more valuable.

If however, you are making a really advanced game, or doing the kind of math that involves solving for pi out to a billion numbers, then you want the program to run as fast as possible.

----------


## ninja9578

Not true.  -s strips unused code, so unused parts of libraries are pulled out.

----------


## khh

> Not true.  -s strips unused code, so unused parts of libraries are pulled out.



I thought that was standard behaviour even without specifying a special parameter?

----------


## ninja9578

Some of it is, but not all of it.  Here's why.  Libraries can be loaded dynamically, meaning outside programs and libraries might use functions within it, even if nothing does internally.  These can't be stripped out.

----------


## slash112

One thing I was wondering. How would you get it to detect a word, or character within a user input?

Like, I know there is this:




```
if (userinput == "fuck");
cout << "omg you swore, you basterd" << endl;
```


But that means the user has to input "fuck" only, and nothing else.

The way I want it would be more like if the person wrote a whole sentence that included the word "fuck", then it would say "omg you swore..."

Just as an example, of course.

----------


## Ynot

```
std::string user_input;
std::cin >> user_input;

found_fuck = user_input.find("fuck");
if (found_fuck != std::string::npos)
{
    std::cout << "omg you swore, you basterd" << std::endl;
}
```

----------


## khh

Firstly what you're trying there won't work. If you want to compare two strings you need to use strcmp() or something. strcmp() is a function that returns the number of characters that are different between two strings. In your example, you could have written
if (!strcmp(userinput, "fuck"))
(don't forget to include string.h/cstring
and it would have worked as you expected.

But in order to search a string containing more than one word, you'd probably have to loop through it and isolate the words (looking for characters that are not letters), and then compare each word against the word you want to detect.

edit: ... Or you can use the built inn find function of the string class, it seems :p

----------


## ninja9578

> Firstly what you're trying there won't work. If you want to compare two strings you need to use strcmp() or something. strcmp() is a function that returns the number of characters that are different between two strings. In your example, you could have written
> if (!strcmp(userinput, "fuck"))
> (don't forget to include string.h/cstring
> and it would have worked as you expected.
> 
> But in order to search a string containing more than one word, you'd probably have to loop through it and isolate the words (looking for characters that are not letters), and then compare each word against the word you want to detect.
> 
> edit: ... Or you can use the built inn find function of the string class, it seems :p



Absolutely not.




```
using namespace std;
string in;
cin >> in;
if (in == "fuck"){
   cout << "in == fuck" << endl;
} else if (in.find("fuck") != string::npos){
   cout << "in contains fuck" << endl;
}
```


strcmp is for char strings, it's C, not C++.  The std::string class has == operators for both other strings and char strings.

----------


## khh

> strcmp is for char strings, it's C, not C++.  The std::string class has == operators for both other strings and char strings.



Well, it's impossible to tell from his post whether he's asking about C or C++ :p

----------


## Ynot

Slash,
rather than asking little questions here
you may be better off looking stuff up in a reference guide
(it'll be quicker, and you'll learn more)

Eg.
Here's the reference for the string class
http://www.cplusplus.com/reference/string/string/

The methods are at the end

----------


## ninja9578

> Well, it's impossible to tell from his post whether he's asking about C or C++ :p



C++, he's using cout  ::tongue::

----------


## slash112

Thanks, guys.

And Ynot, I never noticed that on the site, that will be very handy. Thanks.

----------


## khh

> C++, he's using cout



Ah. Busted.
Oh well, I guess I should only answer questions I'm sure about. Though luckily there's always someone here to inform me when I'm wrong :p

----------


## ninja9578

lol, no don't do that.  If I correct you then you learn more  :smiley:

----------


## slash112

Well. I would like to know how Guitarboy is coming along.

So, Guitarboy? Still at it?

----------


## guitarboy

Err, not very good at it.
Trying, but failing.

----------


## ninja9578

Aww, oh noes  :Sad:   What are you stuck on?

----------


## guitarboy

I'm not reall quite sure what I should be doing/learning. I'm going to take classes soon (a month, probably) so I'm going to wait until then.

----------


## Replicon

> I'm not reall quite sure what I should be doing/learning. I'm going to take classes soon (a month, probably) so I'm going to wait until then.



You know, the first few problems on http://projecteuler.net/ are actually really easy, and perfect for you to practice if you don't really have anything to practice with.

----------

