Hard Light Productions Forums

Modding, Mission Design, and Coding => FS2 Open Coding - The Source Code Project (SCP) => Topic started by: Freespace Freak on September 12, 2006, 07:56:52 am

Title: I wrote my first bit of source code!
Post by: Freespace Freak on September 12, 2006, 07:56:52 am
I'm enrolled in a class called Engineering Computations, but it's actually a class where we learn how to write source code using C and C++.  I didn't "invent" the code, the teacher did, but he baby-stepped how to write it and put it into C++.  It's nothing fancy, it's just a System32 dll console program that calculates the area and volume of a cylinder given two inputs: height and radius.  But I'm learning how to write REAL source code, and maybe one day I'll write some code for the SCP!  :D
Title: Re: I wrote my first bit of source code!
Post by: karajorma on September 12, 2006, 08:19:27 am
Sounds good. Just don't go downloading the FS2 source just yet cause you'll be clawing out your eyes and burning your compiler by the end of the week.

Look forwards to possibly seeing you on the team in a few months though.
Title: Re: I wrote my first bit of source code!
Post by: Colonol Dekker on September 12, 2006, 08:23:38 am
FreespaceFreak, i expect at least 1500 new lines of code by half past five completely renovating the SCP.



<joke :D >

congrats at volumetric thingy  :yes:
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 12, 2006, 08:29:49 am
I have a student version of C++ that comes with the book, and it doesn't allow me to distribute programs built with it.  I think I'll buy my own compiler soon, though.  You guys probably use Java, right?  Since it's cross platform and all.  My professor told me it's essentially identical to C++ anyway.
Title: Re: I wrote my first bit of source code!
Post by: Shade on September 12, 2006, 09:51:41 am
Your teacher is on crack :p They're similar in many ways, but there are also massive differences.

The FS_open source code is c/c++, and there are actually some choices of free windows compilers that can work with it with some tweaking (there's two threads stickied at the top of the forum explaining what's needed for that). And of course, it also works with gcc and anything based on it if you've got a linux/mac system. It's probably a good idea to at least try one of those options before spending money, since as Karajorma said, you may just decide to claw your eyes out after perusing the code and, well, it'd be a shame to have spent money if that's how it ends ;)

Oh yeah, and feel free to ask questions if you've got trouble getting the free alternatives to work. Some of us have been there and done that, and should be able to answer most of them.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 12, 2006, 11:33:13 am
Why would viewing thw code in C++ make me want to claw my eyes out? :nervous:
Title: Re: I wrote my first bit of source code!
Post by: Lord Platin on September 12, 2006, 11:55:16 am
It's like reading a really advanced maths book. You see the signs, understand most of them, understand even those little number-thingies but you have no clue what all this together does ^^ Now that would be ok, but what would happen if someone put the pages in a completely random order?

And NOW you have FSSCP-code :) Looked at it once and it was... interesting...

EDIT: I think my favorite part of the few things I looked at was the turret-code or something like that...
Title: Re: I wrote my first bit of source code!
Post by: karajorma on September 12, 2006, 01:18:29 pm
Yep. The FS2 code is....interesting.

Especially if you're being trained (as you no doubt are) in Object Oriented programming. For a start most of the code is C not C++ There is barely any use of classes or objects the way you'll be learning to use them.

All in all it's a very old school method of programming.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 12, 2006, 01:36:47 pm
Yep. The FS2 code is....interesting.

Especially if you're being trained (as you no doubt are) in Object Oriented programming. For a start most of the code is C not C++ There is barely any use of classes or objects the way you'll be learning to use them.

All in all it's a very old school method of programming.

Actually, my prof is teaching us C and not C++, at least he says "we probably are not going to get to C++ during the breadth of this course."  However, he said if you know C, then C++ is easy, and so is Java.  They just take a little getting used to.
Title: Re: I wrote my first bit of source code!
Post by: taylor on September 12, 2006, 02:13:44 pm
All in all it's a very old school method of programming.
Which is why I like it so much. :D
Title: Re: I wrote my first bit of source code!
Post by: Mongoose on September 12, 2006, 02:22:20 pm
One of these days, I really need to get around to taking a look at the code myself.  I took a semester of C and one of C++, and I'm currently in a class teaching data structures using C++, though it sounds like those wouldn't be much use in terms of FS2.  Granted, I have absolutely no clue how the hell one progresses from coding command-line-based programs capable of reading and sorting text data to programming for a 3D commercial game, but I figure, what the hell? :p Can't hurt for me to look at it and see if I have any clue as to what's going on.  And who knows; I might be able to help out in some miniscule way someday.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 12, 2006, 02:23:12 pm
All in all it's a very old school method of programming.
Which is why I like it so much. :D

Since I'm learning C, not C++, right now, I did notice that a lot of the work I've done so far, such as editing and adding to tables and such, is very similar to what I'm doing in class.
Title: Re: I wrote my first bit of source code!
Post by: Flipside on September 12, 2006, 03:15:37 pm
I'm starting a course on Monday which is Computing and Multimedia, it's going to involve Java programming, apparently, making the jump from Java to C++ is not too hard, and since I want to start learning to code in C++ anyway, I will certainly be making the jump :)
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on September 12, 2006, 03:43:01 pm
All in all it's a very old school method of programming.

Which is why I like it so much. :D

Me too. :D

The fact that sexps are based on LISP is just icing on the cake. :D :D :D
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 12, 2006, 04:28:14 pm
Ha, Flipside.  Back in the day there was a guy in my band we used to call Captain Caveman, cause he was hairy! :D
Title: Re: I wrote my first bit of source code!
Post by: karajorma on September 12, 2006, 05:45:08 pm
All in all it's a very old school method of programming.

Which is why I like it so much. :D

Me too. :D

The fact that sexps are based on LISP is just icing on the cake. :D :D :D

Bah. You're both obviously insane. :p

I prefer not having to worry which one out of 500 global variables I need to worry about :D
Title: Re: I wrote my first bit of source code!
Post by: Flipside on September 12, 2006, 08:15:20 pm
Ha, Flipside.  Back in the day there was a guy in my band we used to call Captain Caveman, cause he was hairy! :D

Lets just say my story involves a Girl's school, a Tarzan outfit and 3 months of detention, and leave it at that :nervous:

I'll hasten to add, this wasn't recently ;)
Title: Re: I wrote my first bit of source code!
Post by: WMCoolmon on September 12, 2006, 08:24:13 pm
Your teacher is on crack :p They're similar in many ways, but there are also massive differences.

The FS_open source code is c/c++, and there are actually some choices of free windows compilers that can work with it with some tweaking (there's two threads stickied at the top of the forum explaining what's needed for that). And of course, it also works with gcc and anything based on it if you've got a linux/mac system. It's probably a good idea to at least try one of those options before spending money, since as Karajorma said, you may just decide to claw your eyes out after perusing the code and, well, it'd be a shame to have spent money if that's how it ends ;)

Oh yeah, and feel free to ask questions if you've got trouble getting the free alternatives to work. Some of us have been there and done that, and should be able to answer most of them.

Though if you're at all serious about it, I highly recommend you look for a copy of Visual C++ Professional or Microsoft Visual C++ .NET 2003. Both of those versions can use optimizing compilers (in the latter case, you have to replace a few files from the Visual C++ toolkit) and are IDEs from the get-go. I've tried the 'free' compilers for Linux, as well as some of the IDEs, and none of them have ever come close to having as effective of an ease of use:capability ratio.

It's also a much better alternative to the toolkit compiler. I tried the 'express' thingy once, but very quickly went back to 2003 standard with the toolkit compiler. (I don't remember exactly why, unfortunately, just that I preferred standard)

VC++.NET is ~$100, VC++ 6 tends towards the used/old software departments of most stores.
Title: Re: I wrote my first bit of source code!
Post by: Mars on September 12, 2006, 10:16:40 pm
Sounds good. Just don't go downloading the FS2 source just yet cause you'll be clawing out your eyes and burning your compiler by the end of the week.

Look forwards to possibly seeing you on the team in a few months though.

I've looked at it, and I have very little programming expirience.... oh God.
Title: Re: I wrote my first bit of source code!
Post by: Backslash on September 13, 2006, 01:01:29 am
 :lol:
It's not THAT bad .......ok yeah it is, IF you look at everything.  The trick is to start small.  Like me, there's no way I'm going to understand the graphics code and such right off the bat, so I decided to look at the HUD code.  From there I slowly began changing little things, then trying my own things by imitating other code in similar functions, then trying my own things, then expanding outward into related code.

My previous experience?  Command-line type stuff.  So Mongoose and you other interested beginners, you can do just fine if you are patient and don't dive in TOO fast.  Pick an area to learn and focus on it... try things, make changes to see what happens, ask questions etc.

I'm learning a lot!  The funny thing is, learning these old school methods will either be beneficial (if I get a job working on old code) or come back to bite me (if I get a job working on new code) :rolleyes:

I echo what WMCoolmon says about the Visual Studio series.  Though, I must say the free 2005 Express Edition works well, and I'd wager if you're NOT already used to the advanced features in the Professional versions (like WMC probably is), it'd fit you just fine.  And you can't beat the price (besides of course the whole YOUR SOUL to Microsoft part... j/k :p)

Hey WMCoolmon, what's this about using the toolkit compiler in MSVC 2003?  I've got 2003... how much does the toolkit compiler help?
Title: Re: I wrote my first bit of source code!
Post by: karajorma on September 13, 2006, 01:52:10 am
Just be warned that for loops do not work as expected in MS compilers.

Code: [Select]
for (int i=0; i < something ; i++)
{
.....
}

i = 0;

That would give a complier error on any compiler other than the MS ones. When you take lessons in scope you'll learn that the variable i is only supposed to be accessible from within the loop itself. On MS compilers that code will work perfectly well with no sign that anything is wrong.
Title: Re: I wrote my first bit of source code!
Post by: Backslash on September 13, 2006, 02:28:03 am
On the bright side that's an option you can set in the Project settings under Language: "Force Conformance In For Loop Scope".

Also, now (afaict) Visual Studio 2005 defaults to that being set Yes. :yes:
Title: Re: I wrote my first bit of source code!
Post by: WMCoolmon on September 13, 2006, 02:34:07 am
The toolkit compiler is actually the one included in the professional edition of 2003 .NET; the standard edition lacks a number of the optimizations available in the professional edition compiler. Installing the toolkit compiler enables these optimizations through use of the manual command line settings; the drop-down boxes and other controls in the standard edition will remain disabled, although the optimizations will still take effect.

For more information, see Xona.com - Visual C++ .NET Standard Edition - Free Optimizing Compiler (http://xona.com/2004/06/29.html).


I have got to cut down on the wiki reading...
Title: Re: I wrote my first bit of source code!
Post by: Herra Tohtori on September 13, 2006, 11:41:22 am
You know what...

I took a Java course during summer. And the tasks we were given made me scream inside my head of how to NOT show the advantages of object-oriented programming...

Most of the time I just wanted to write a ****ng long main method that would simply do the program. All those method calls and null pointers and what not were driving me crazy. It obviously is more of an advantage when the coding gets more advanced, methods get longer and classes grow exponentially measured in code lines... Then it starts to be a good thing to have the code in separate objects.


But writing a program wwhich has a main method that asks for information, area size calculating method, volume calculating method AND an output method (StringTo) is just frustrating, it adds many things to code that are actually not needed and complicates the coding process quite a bit.

I wrote more complex programs in Texas Instruments TI-86 in high school. One of them prompted to feed in several variables (initial velocity, starting height, direction, mass and radius to name most important) and counted the trajectory of a ball thrown in air. It took air friction in account and used some pretty nice features of the calculator. It drew the trajectory in calculator's own parametre function screen, and then paused, and after pressing a key it printed a screen of information including maximum height, distance of impact from the start point (on x-axis), impact velocity and impact angle. :nervous: Sadly, the program memory was purged before the final exams and I forgot to write it down on more static format. I could write it again, though. It wouldn't take that much time...

I suppose it can't be that much more difficult to do C programming than programs with TI-86... learning the syntax just takes time and effort and getting fast demands a lot of time and excersizes. :nod:
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 13, 2006, 06:33:28 pm
Yeah, I wrote some programs with my TI-84, but I like the formatting in C.  I like how it makes expandable + and - boxes and has stuff with a $ or # sign in blue and the dev comments in green.  It makes looking for stuff easy(er), at least from the standpoint of a guy who's never done any real hard-core programming before.  I did take a BASIC course back in high school.  Not Visual BASIC, but BASIC 1.0.  That was old school!  We used computers that were built when I was born.  To say the school had a low tech budget would be an understatement.  For our final exam we had to write the code to make the game Pong!
Title: Re: I wrote my first bit of source code!
Post by: Herra Tohtori on September 13, 2006, 06:40:59 pm
What program are you using to actually write the code?

I use Eclipse with Java, it also has different colours and it does the indentions automagically when you enter something inside, say, wave brackets... There are instructions on how to use Eclipse on C and C++ programming, too.

http://www.eclipse.org/ (http://www.eclipse.org/)

How to Use Eclipse for C and C++ Development (http://www.drdobbs.com/dept/cpp/192600530) (link also in the main page of eclipse.org)

Title: Re: I wrote my first bit of source code!
Post by: ME$$ENGER on September 14, 2006, 04:59:50 pm
My IDE of choice is Eclipse, too. Sometimes a bit of DrJava to get a quick check on the code using the interaction pane.

I only code in Java & Python, though. Maybe I should teach myself C someday.
Title: Re: I wrote my first bit of source code!
Post by: Ferret on September 14, 2006, 05:46:28 pm
Yeah Eclipse is a seriously good IDE, I'm using it for PHP right now.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on September 14, 2006, 05:51:29 pm
Just wish Eclipse didn't run a like a hog though   :blah:
Title: Re: I wrote my first bit of source code!
Post by: Turey on September 14, 2006, 07:02:57 pm
Just wish Eclipse didn't run a like a hog though   :blah:

yeah, that really sucks when you're running it on a less than top-of-the-line comp.

i've done a lot of basic code, quite a bit of C code, and a small amount of java. I'll look over the code and see if i can help at all.


EDIT: Has anyone compiled the source with eclipse? I haven't used it for C programming before (All my previous C programming was in MPLAB) If you've gotten it to compile in eclipse, could you explain how?
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 15, 2006, 10:39:21 pm
What program are you using to actually write the code?

I use Eclipse with Java, it also has different colours and it does the indentions automagically when you enter something inside, say, wave brackets... There are instructions on how to use Eclipse on C and C++ programming, too.

http://www.eclipse.org/ (http://www.eclipse.org/)

How to Use Eclipse for C and C++ Development (http://www.drdobbs.com/dept/cpp/192600530) (link also in the main page of eclipse.org)



Er, win32 console application, I think.  I just installed Visual C++ introductory edition on my PC, but I can't recreate what I did in class.  I guess I didn't take good enough notes.  :nervous:
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 30, 2006, 03:28:48 pm
I made my first C program, all by myself.   :)  Again, it's a Win32 console app, and I wrote it in both C and C++ so I can understand C just for the SCP!  It's pretty simple, though.  Here it is, if you're interested.

Code: [Select]
#include<stdio.h>
int main ()

{

//Declare Variables

const double PI=3.1415926536;
const double r_earth=6371000;
double X0; //extra length
double c_earth; //circumference of earth (constant)
double c_band, r_band, height; //calculated values

//Input Data
printf("\n HEIGHT OF HYPOTHETICAL ELASTIC BAND");
printf("\n\n Suppose an inelastic band was to be fitted around the circumference of");
printf("\n the Earth at the equator.  If this band was to be cut and had an additional");
printf("\n length added to it, it would be a certain heigth above the surface of the");
printf("\n Earth, if it could float freely.");
printf("\n\n This program calculates the height of that band, given the length inserted.");
printf("\n\n Enter extra length of band in meters:");
scanf("%lf", &X0);

//Calculate
c_earth = 2 * PI * r_earth;
c_band  = c_earth + X0;
r_band  = c_band / (2 * PI);
height  = r_band - r_earth;

//Output Data
printf("\n Height of band: %8.7f meters", height);
printf("\n\n");
return (0);
}
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on September 30, 2006, 03:57:30 pm
Looks good. Although I'd put the \n at the end rather than the front, but thats just a nitpick. 

BTW is scanf("%lf", &X0) overflow safe?  (Otherwise strlin >> X0 would work)
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 30, 2006, 04:53:38 pm
Looks good. Although I'd put the \n at the end rather than the front, but thats just a nitpick. 

BTW is scanf("%lf", &X0) overflow safe?  (Otherwise strlin >> X0 would work)

%lf and &X0 are C-style formats, while >> X0 and such are C++.  What we call C exist nowadays within C++ compilers, it's just referred to as standard C formatting.  scanf, printf and such are examples.  One of the big advantages that C has over C++ is that you can get it to output exactly the way you want it to without using iomanip.h.  It even does it better than iomanip.h can in fact, all without having to include a seperate .h.  C uses stdio.h, while C++ uses iostream.h.  Here's a copy of the exact same program in C++.

Code: [Select]
//Setup

#include<iostream.h>

int main ()
{

//Declare Variables
const double PI=3.1415926536;
const double r_earth=6371000;
double X0; //extra length
double c_earth; //circumference of earth (constant)
double c_band, r_band, height; //calculated values

//Input Data
cout << "\n HEIGHT OF HYPOTHETICAL ELASTIC BAND";
cout << "\n\n Suppose an inelastic band was to be fitted around the circumference of";
cout << "\n the Earth at the equator.  If this band was to be cut and had an additional";
cout << "\n length added to it, it would be a certain heigth above the surface of the";
cout << "\n Earth, if it could float freely.";
cout << "\n\n This program calculates the height of that band, given the length inserted.";
cout << "\n\n Enter extra length of band in meters:";
cin  >> X0;

//Calculate
c_earth = 2 * PI * r_earth;
c_band  = c_earth + X0;
r_band  = c_band / (2 * PI);
height  = r_band - r_earth;

//Output Data
cout << "\n Height of band: "<< height << "meters";
cout << "\n\n";
}
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on September 30, 2006, 05:22:21 pm
I was mostly worried about the scanf's overflow security.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on September 30, 2006, 05:29:25 pm
I was mostly worried about the scanf's overflow security.

Not really sure what that is, all I know is that it works without any errors or warnings, except it complains that I don't have anything written in the parenthesis for int main.

Edit:  %lf and &X0 are actually very necessary in standard C format.  "%lf"  tells the computer to assign a long float (long double) number to memory (I actually could have used just "%f" since f, for float, includes double), and the & sign tell the computer to reference that memory location as being whatever follows the & sign, which in this case is X0.  >> X0 wouldn't work because <stdio.h>, which is the standard C format, won't understand it.
Title: Re: I wrote my first bit of source code!
Post by: Spicious on October 01, 2006, 09:33:15 am
Doesn't scanf have overflow problems just with strings?

%f doesn't work for doubles with scanf.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 01, 2006, 01:31:30 pm
Doesn't scanf have overflow problems just with strings?

%f doesn't work for doubles with scanf.

For strings in C, you make %s.  I respectfully point out that you're wrong on the doubles thing, at least according to the manual right here.  For float and double float, you use %f.  For long double you use %lf.  If you doubt me, then compile the code and run it under win32 console app.  It works, trust me.
Title: Re: I wrote my first bit of source code!
Post by: WMCoolmon on October 01, 2006, 07:07:30 pm
http://www.cplusplus.com/ref/cstdio/scanf.html
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 02, 2006, 01:32:03 pm
That's exactly the same reference my proffesor pointed me to.

I retract my earlier statement.  %f is for float, %lf is long float, aka double, and %Lf is for long double.  I'm still not seeing what you're saying about overflow control, though.  As far as I know, if you use << or >> in stdio.h the compiler simply won't understand wtf you're talking about, although I think iostream.h will understand scanf and printf and such.

Heh, I'm getting good at this.  I just wrote another program that calculates the square yardage of concrete needed to build a circular walkway around a garden, given the diameter of the garden, the width of the walkway, and the desired thickness of the walkway.  Works like a charm.   :)
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 02, 2006, 03:48:27 pm
Ignore it then.. it must be just strings that you need to worry about buffer overflow then.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 02, 2006, 03:51:14 pm
Oh, I forgot, here's the program for those who are interested.

Code: [Select]
#include<stdio.h>
#include<math.h>
int main (void)

{

//Declare Variables
double d; //diameter of garden
double w; //width of walkway
double ti; //width in inches
double t; //width in feet
double r; //calculated radius of garden
double R; //calculated outer radius of walkway
double dei; //extra measurement for garden diameter in inches
double wei; //extra measurement for walkway width in inches
double d_extra; //dei converted into feet
double w_extra; //wei converted into feet
double V; //volume of concrete needed in feet
double answer; //the end result converted into square yards
double R2; //R squared
double r2; //r squared
const double PI=3.1415926536;

//Input Data
printf ("\n *********************GARDEN WALKWAY CALCULATOR*********************");
printf ("\n\n This program calculates in square yards the amount of concrete needed to");
printf ("\n build a circular walkway around a circular garden.");
printf ("\n You will be prompted to input the diameter of the garden in feet,");
printf ("\n then any additional measurement in inches.");
printf ("\n Then you will be asked to input the width of the walkway in feet and inches");
printf ("\n followed by the thickness of the walkway."); 
printf ("\n Please input the inches measurement in decimal form.");
printf ("\n For example, input 6 1/2 inches as 6.5.");
printf ("\n\n Diameter of Garden.");
printf ("\n Feet:");
scanf  ("%lf", &d);
printf (" Inches:");
scanf  ("%lf", &dei);
printf ("\n Width of Walkway.");
printf ("\n Feet:");
scanf  ("%lf", &w);
printf (" Inches:");
scanf  ("%lf", &wei);
printf ("\n\n Thickness of Walkway.");
printf ("\n Inches:");
scanf  ("%lf", &ti);

//Calculate
d_extra=(dei)/12;
w_extra=(wei)/12;
r=(d+d_extra)/2;
t=(ti)/12;
R=r+(w+w_extra);
R2=pow(R,2);
r2=pow(r,2);
V=PI*t*(R2-r2);
answer=V/3;

//Output Data
printf ("\n Radius of Garden: %4.2lf feet.", r);
printf ("\n Radius of Walkway from center of Garden: %4.2lf feet.", R);
printf ("\n\n Amount of concrete required: %4.2lf cubic yards.", answer);
printf ("\n\n");
return (0);
}
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 02, 2006, 04:05:20 pm
Looks like we have a future SCP coder  :nod:

(btw personally I'd give those variables a better name than just "d", "w", "t", like (gardenDiameter, walkwayWidth).. but thats just me  :D )
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 02, 2006, 04:15:38 pm
Looks like we have a future SCP coder  :nod:

(btw personally I'd give those variables a better name than just "d", "w", "t", like (gardenDiameter, walkwayWidth).. but thats just me  :D )

Yeah, I would for longer programs, especially ones with more than one int I guess they're called.  I haven't started on stuff like that, though.
Title: Re: I wrote my first bit of source code!
Post by: Cyker on October 02, 2006, 05:54:39 pm
Ahh... wait 'til you start writing code for Windows or to do graphics!!

That'll have you tearing your hair out :D

I learned Windows API in C, and to create a simple window needs about 5 pages of code!  :eek:

Luckily there are lots of 'helper' libraries for that, but unfortunately they're all C++ which means they're brain damaged

(For the record, I hate C++ - I think the class system syntax was actually designed to Kill Programmers via brain haemorrages or something. Java and C# are so much nicer to wrote code for!! Its just a pity they both only run via virtual machine emulation, and are thus damned slow...)



BTW... do they still teach people to strcture functions like:

void function(int param)
{
//stuff
}

Instead of :
void function(int param){
//stuff
}

?

Why is that? I've seen that cause so many problems, Like the famous:

while(i<50);
{
printf("%i",i++);
}
//Why won't this code do what you'd expect it to do? ;)

Yet everyone still uses that style except (it seems!) me!!
(When I coded that is ;)  I haven't done any serious codeing in ages :()
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 02, 2006, 06:32:07 pm
Personally I hate:

void function(int param){
//stuff
}

It's bad for indenting, you lose balance doing it that way..  Where's the "{"?

Something like this:

Code: [Select]
while (i != 10){
     work = computeValue(i) ;
     while (work != 0)
              force = computeStrength (work);
              if (force > MAXforce){
                     ShowAlert () ;
                      return ;
              }
              work-- ;
     }
}

Java seems to be the worst offender.
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on October 02, 2006, 06:37:30 pm
Ahh... wait 'til you start writing code for Windows or to do graphics!!

That'll have you tearing your hair out :D

I learned Windows API in C, and to create a simple window needs about 5 pages of code!  :eek:

Luckily there are lots of 'helper' libraries for that, but unfortunately they're all C++ which means they're brain damaged

(For the record, I hate C++ - I think the class system syntax was actually designed to Kill Programmers via brain haemorrages or something. Java and C# are so much nicer to wrote code for!! Its just a pity they both only run via virtual machine emulation, and are thus damned slow...)



BTW... do they still teach people to strcture functions like:

void function(int param)
{
//stuff
}

Instead of :
void function(int param){
//stuff
}

?

Why is that? I've seen that cause so many problems, Like the famous:

while(i<50);
{
printf("%i",i++);
}
//Why won't this code do what you'd expect it to do? ;)

Yet everyone still uses that style except (it seems!) me!!
(When I coded that is ;)  I haven't done any serious codeing in ages :()

Not sure what you're asking here.  If you're referring to brace alignment style, people should IMO teach the BSD/Allman style (where the braces are aligned in the same column), as it's superior in both readability and syntactical consistency.

Incidentally, you added an erroneous semicolon in your second example.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 02, 2006, 06:46:39 pm
Well Goober agrees with me  :D

Btw how do you guys feel about the old Hungrain notation? I.E.   

bool bIsFound ; 
int iSpeed ;
char cData ;


I used to like it, but have grown out of it. 
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on October 02, 2006, 07:06:57 pm
Ugh.  I hate Hungarian notation.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 02, 2006, 07:12:27 pm
We agree again  :D

bInfo   what b byte/boolean?
How do you do class instances?  Thats why I quit using it..  Plus FXCop flags them as out-of-date.
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 02, 2006, 09:29:44 pm
If you're referring to brace alignment style, people should IMO teach the BSD/Allman style (where the braces are aligned in the same column), as it's superior in both readability and syntactical consistency.
Speak for yourself.  I hate it, primarily for readability reasons. :)

I hate it more that the three of you (Goober, WMC, kara) tend to change existing :v: code to also use that brace style, but whatever.  I'm from the "porting" school of coding, which means that you have no coding style except for the style of the code your working with.  If this was an icculus.org project then all of your code which doesn't conform to existing formatting would be rejected until you did it properly.  Which is why I format my code the way that I do, and will continue to do for all of my FSO work. :D

We do agree on Hungarian notation though.  Yuck.  :ick:
Title: Re: I wrote my first bit of source code!
Post by: Backslash on October 02, 2006, 11:37:23 pm
Heh, now I'm confused... what's the :v: code style then?  I thought I had figured it out but it sounds like most of the code I've been looking at has been changed.  Or which style should I use when committing?

Is there a particular name for the style used in FSO code?
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on October 02, 2006, 11:52:00 pm
I hate it more that the three of you (Goober, WMC, kara) tend to change existing :v: code to also use that brace style, but whatever.  I'm from the "porting" school of coding, which means that you have no coding style except for the style of the code your working with.

Well, I like my code neat and organized, thank you very much. :D

Incidentally, every now and then I come across a snippet of :v: code which is actually incredibly hard to read until I format it properly.  The rest of the time, it's either out of habit or because I'm in a spring cleaning mood. ;)

Quote
If this was an icculus.org project then all of your code which doesn't conform to existing formatting would be rejected until you did it properly.

No kidding?  That's a good way to... if not drive certain coders away, at least create the potential for a lot of conflict.  Hmm...

EDIT: I sound like a noob.  Of course it creates the potential for a lot of conflict.  I need to read up on software engineering standards a little bit more than the advantages and disadvantages of certain styles. :)
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 03, 2006, 12:05:12 am
Heh, now I'm confused... what's the :v: code style then?
K&R is what most (+95%) the :v: code is in.  Usually only when readability greatly benefits from it does the code deviate from this (like with a multi-line if() statement for instance, it's just easier to read with BSD/Allman style).  And of course using (4-space) tab indention is the FS norm.

I generally prefer K&R in the first place since I hate too much white space.  I like to see more code on the screen at one time, not more "{" and nothing else on a line.  Screen real estate is important to me and BSD/Allman wastes it like nothing else.  I do prefer BSD/Allman for switch() statements though since that is the one thing that I feel benefits greatly from it, readability wise.

I also use Anjuta (on Linux obviously), which is great for stuff like this since it allows you to collapse blocks into a single line, and it shows a vertical line to help you link up the code blocks with a quick glance.  IDE/editor does make a difference on how readable the various formats are.  MSVC uses BSD/Allman by default, so it's likely easier to read that.  MSVC also sucks, so take that how you want. :)

(see http://en.wikipedia.org/wiki/Indent_style if you want to see more about the various indent styles)


Well, I like my code neat and organized, thank you very much. :D
I do too, but I don't find those sorts of changes neat or organized.  :p  ;)

No kidding?  That's a good way to... if not drive certain coders away, at least create the potential for a lot of conflict.  Hmm...
Actually, that's a big reason why there aren't more Linux coders involved with the SCP.  You changing the formatting style for a particular block of code irks us seriously.  Using different formatting styles hurts overall readability, which is why when working with an existing code base, you stick to the existing style as much as possible.  A good coder will adapt to the code, not adapt the code to themselves.  :)
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 03, 2006, 12:20:51 am
On the wiki list:
BSD is the best, followed by GNU and K&R, BSD/KNF are the second worst, Pico is hidieous.

I hate formatting, coding that is one big paragraph... break it up Please! Screen space isn't that important anymore

This also includes 80 col. Theres nothing worse than having a long section and it cuts down to a second line only to have a little piece  :rolleyes:

Code: [Select]
     Result = SomethingTakesALittleMoreThan80 (parameter1, parameter2,
                                               parameter3) ;


And MSVC does BSD GNU great, since you can collapse code sections very nicely.  I also like C#'s regions, you can also use comments on those regions.  It helps hide the unimportant information.
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 03, 2006, 01:58:26 am
On the wiki list:
BSD is the best, followed by GNU and K&R, BSD/KNF are the second worst, Pico is hidieous.
What's "best" is irrelevant and 100% coder preference.  You use what works for the code, which means that you don't change formatting in an existing project.  Personal preference isn't worth a damn unless it's your own project.  K&R is the most common C formatting style, BSD/Allman is the most common C++ formatting style.  Being from a C background I greatly prefer K&R because it's what I'm use to.  But I'll use whatever any existing code base is formatting with regardless of my personal preference.

I hate formatting, coding that is one big paragraph... break it up Please! Screen space isn't that important anymore

This also includes 80 col. Theres nothing worse than having a long section and it cuts down to a second line only to have a little piece  :rolleyes:
I hope that you re-read those two lines and realize how stupid that is.  The first sentance totally contradicts the second.  If vertical screen space isn't important, then neither is horizontal screen space.  Especially when you consider that there exists more horizontal screen space than vertical screen space.  But it's irrelevant regardless since in an existing code base you should use the same formatting style as the existing code.

I prefer to conserve vertical screen space and use more horizontal screen space (which is usually something that you can get away with regardless of other formatting).  Horizontal spacing issues hinder readability far more than vertical spacing does.  I don't stick to 80 column (except usually for comments), but I don't like to go over 160 either.

And MSVC does BSD GNU great, since you can collapse code sections very nicely.
Like I said, MSVC caters to BSD/Allman since it's the default formatting style in MSVC.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 03, 2006, 02:33:29 am
This is kinda what i mean by spacing:
Code: [Select]

void DoSomething () {
    int loop=0;
    int processed=0;
    bool done=false;
    while (!done) {
         done=StartProcessing(loop, &processed);
         if (processed == MaxLimit){
            done=true ;
    }
}


I don't know about you, but I'm quite visual when it comes to coding.  Clustering ideas together apart from each other.

Code: [Select]
void DoSometing ()
{
     int loop = 0 ;
     int processed = 0 ;
     bool done = false ;

     while (!done)
     {
           done = StartProcessing (loop, &processed) ;

            if (processed == MaxLimit)
            {
                  done = true ;
            }
     }
}


albiet if (processed) and done= true can be collapsed into one statement, but you get the idea.

As for the 80 column, i totally agree with you, but i know people that'll chew us out for evening going to 81. I'd rather not have my code look like a bad cross between cobol and asm. LOL  I'll keep my bad cross mixes to my models  :lol:
     
Title: Re: I wrote my first bit of source code!
Post by: Cyker on October 03, 2006, 02:45:46 am
Aww crap... did I just start a flame war?!  :eek:

Erm....

So what about that Haskell 'eh guys? Erm...

*runs and hides*

while(i<50);
{
printf("%i",i++);
}
//Why won't this code do what you'd expect it to do? ;)

Yet everyone still uses that style except (it seems!) me!!
(When I coded that is ;)  I haven't done any serious codeing in ages :()

Not sure what you're asking here.  If you're referring to brace alignment style, people should IMO teach the BSD/Allman style (where the braces are aligned in the same column), as it's superior in both readability and syntactical consistency.

Incidentally, you added an erroneous semicolon in your second example.

Very good! That is the correct answer to the problem! :D

The mark of an experienced coder ;)

That is the problem with the in-column {}'s - Its very easy to do stuff like that and miss off a semi but still have the code compile and run because it is perfectly valid code.

If you miss off a brace, the compiler will usually throw up at least a warning about an unmatched brace somewhere...

If you're used to it, there are no readability problems - You look for indentation blocks, not tiny curly braces ;)
I don't know what syntactical consistency means...

I use KATE (The KDE editor) to write most of my code - Most IDEs really suck at the resolutions I work at (800x600 - *Much* more comfortable on the eyes for staring at text for long periods.), but KATE handles long-line wrapping very well and intelligently.


At the end of the day, its coder preference, but that can be problematic in a team (Once in uni, we got so hung up about it we wasted time making utilities to switch between the two styles before we actually started working on the project proper!!!  :eek: :D)



Code: [Select]
void DoSomething() {
    int loop=0;
    int processed=0;
    bool done=false;

    while(!done) {
         done=StartProcessing(loop, &processed);

         if (processed == MaxLimit){ //An unneeded brace...
            done=true;
         } //... or missing a brace :D

    }
}

Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 03, 2006, 02:54:23 am
Do you use GNU or K&R? Do you UVmap during or after you've finished the model. 

The equivalent of a religous war for coders/modelers  :lol:
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 03, 2006, 03:00:34 am
My preferred style is closer to this:

Code: [Select]
void DoSomething()
{
    int loop = 0;
    int processed = 0;
    bool done = false;

    while ( !done ) {
         done = StartProcessing(loop, &processed);

         if (processed == MaxLimit)
            done=true;
    }
}

Notice the spaces around the =, and the spaces on the while () as I do that with ! checks since it's usually easier to see the ! that way, and I don't normally like to use brakes on a single line if or ifelse.

I agree with on everything else though, except the flame war.  If this were a flame war then you wouldn't have replied, for fear of death. :D

You are in trouble for the Haskell remark however, I just threw a shoe at you.  Not really sure when it will get there, but when it does at least do me the courtesy of not ducking.  ;)
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 03, 2006, 03:09:13 am
Outside the placement of the "{" and your spacing [especially around the ";" and "(", it looks very much like my work.
Yes I sometime leave off the {} from a single line, depending on how i feel.  I see what you mean about the () around the !. 

It could be worse... he could be doing Haskell AND Hungarian notiation  :lol:

Worse yet.... it could be Perl style

Code: [Select]
void DoSomething () { int loop=0;int processed=0;bool done=false;while(!done){done=StartProcessing(loop,&processed);done=(processed==MaxLimit);}}
Title: Re: I wrote my first bit of source code!
Post by: karajorma on October 03, 2006, 04:12:26 am
Ugh.  I hate Hungarian notation.

Can't say I blame you.

I agree with you on the braces too.
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 03, 2006, 04:15:41 am
Outside the placement of the "{" and your spacing [especially around the ";" and "(", it looks very much like my work.
Actually the spacing (like "while (" instead of "while(") is done more for functional reasons rather than readability reasons, in my case at least.  It makes word selection easier in many editors so that you could get the "while" but not the "(" if that was your intention (you can probably double-click on my examples there to see what I'm talking about).  I think that I started always doing that a few years ago and I do it now without even thinking about it.

It could be worse... he could be doing Haskell AND Hungarian notiation  :lol:
Dude, don't even joke about that.  :shaking:

 :D

Worse yet.... it could be Perl style

Code: [Select]
void DoSomething () { int loop=0;int processed=0;bool done=false;while(!done){done=StartProcessing(loop,&processed);done=(processed==MaxLimit);}}
We affectionately refer to that as "Bobboau" style.  Well, except that everything is spelled correctly in your case.  And of course you need to use comments below the code in question sometimes, and above the code in question other times.  And use different indention for random code blocks, or no indention at all for random lines in the middle of a function.  Oh, and there should have been at least 5 bugs in that code snippet.

(...waits a few mintues for Goober to pick himself up off of the floor...)

Sorry, couldn't resist the joke at your expense there Bobboau. ;)
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 03, 2006, 05:07:08 am
HAHAHAHA
 :wakka:
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on October 03, 2006, 09:03:49 am
(...waits a few mintues for Goober to pick himself up off of the floor...)

You misspelled "minutes" there. ;)

I agree with on everything else though, except the flame war.  If this were a flame war then you wouldn't have replied, for fear of death. :D

This poses a moral conundrum, because my SCP philosophy "Taylor Is Always Right" has the potential to spectacularly conflict with my general code formatting philosophy "BSD/Allman Bracing Is The Way To Go".  So far I've managed to avoid the issue. :D
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 03, 2006, 09:24:46 am
You misspelled "minutes" there. ;)
Yeah, luckily I managed to go back and spell "up" properly before posting though.  That would have been rather embarassing.  But at least you haven't (yet) pointed out all of the other stuff that I've managed to misspell, or just get grammatically incorrect, in this thread.  ;)

This poses a moral conundrum, because my SCP philosophy "Taylor Is Always Right" has the potential to spectacularly conflict with my general code formatting philosophy "BSD/Allman Bracing Is The Way To Go".  So far I've managed to avoid the issue. :D
Hmm, that one does pose something of an issue.  Just go with "Taylor Is Almost Always Right", and then that "BSD/Allman Bracing Is Not The Way To Go".  That way everyone wins.  Well, I win at least.  But that tends to be normal, you get used to it. ;)  :D

Though techically I have no problems with "BSD/Allman Bracing Is The Way To Go", just the "I'm Going To Use BSD/Allman In An Existing Code Base That is Almost Entirely K&R" part.

Wait, why the hell are we doing the every-first-letter-is-capitalized thing again?  I'm sure that there must be a reason, since all of this is rather strange otherwise.
Title: Re: I wrote my first bit of source code!
Post by: karajorma on October 03, 2006, 09:57:34 am
To be honest I've used both K&R and BSD/Aliman in the past. I can quite happily use either but on a personal level I find the latter the easier to read.
Title: Re: I wrote my first bit of source code!
Post by: Cyker on October 03, 2006, 11:06:40 am
...

You are in trouble for the Haskell remark however, I just threw a shoe at you.  Not really sure when it will get there, but when it does at least do me the courtesy of not ducking.  ;)

Erm... PASCAL! Yes! I typed PASCAL but... erm... I was... using... a Dvorak keyboard! Yes! That's the ticke-OOF!


Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 03, 2006, 11:51:11 am
Er, does my code look "pretty?"   :nervous:
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 03, 2006, 04:23:44 pm
It's readable... thats the key thing... weither it's K&R or GNU thats irrealavant.  As long as your not becoming a perl programmer on us  :lol:
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on October 03, 2006, 07:38:54 pm
Yeah, luckily I managed to go back and spell "up" properly before posting though.  That would have been rather embarassing.  But at least you haven't (yet) pointed out all of the other stuff that I've managed to misspell, or just get grammatically incorrect, in this thread.  ;)

Eh, I mostly do that to tweak newbs, or other people getting on my nerves. ;) I adapt myself to the forum grammar, except where I have an opportunity to refactor it. :p

Quote
Wait, why the hell are we doing the every-first-letter-is-capitalized thing again?  I'm sure that there must be a reason, since all of this is rather strange otherwise.

It's a common convention on the Internet to put Things That Are Important in title case, isn't it?  Occasionally with a â„¢ symbol at the end of the line? ;)

Let me revisit some things I didn't have time to address before:

I generally prefer K&R in the first place since I hate too much white space.  I like to see more code on the screen at one time, not more "{" and nothing else on a line.  Screen real estate is important to me and BSD/Allman wastes it like nothing else.

Ya, but IMHO less white space makes things more cluttered.  When the code is all bunched up like that (unless it's in a nice orderly if... else if... chain) it runs together and becomes hard to follow.  When scrolling is as simple as a flick of the mouse wheel, or a tap of the Page Up/Page Down key, whitespace is A-1 SUPAR.

Quote
MSVC uses BSD/Allman by default

As an aside, I have a hunch that MSVC uses BSD/Allman not from any evaluation of the merits of the code style but simply because they want to be "different" than Java, which uses K&R in their style manual.

Quote
Actually, that's a big reason why there aren't more Linux coders involved with the SCP.

That's... surprising.  Interesting.  But apparently Linux coders prefer mailing lists to forums too, so we've got several strikes against us. :p

Quote
A good coder will adapt to the code, not adapt the code to themselves.  :)

Now I both agree and disagree with that.  I agree that a coder should be able to mentally adapt to whatever situation he finds himself in.  If you're not flexible enough to work within the constraints you have -- whether it's a matter of code style or design style or programming paradigm or library or what have you -- you're not going to achieve much.  But the coder should definitely adapt the code to themselves, or at least to proper design guidelines.  Basically, if you find crappy code, you should refactor it.  If you find a bug, you should fix it.  If you find a design flaw, you should redesign it.  If you find a huge function that converts uppercase to lowercase using a gigantic switch statement, you should refactor that into a function.  (I actually ran into a similar situation in the localization library in FS2 once.)  And, IMHO, if you find a section of code that looks messy and hampers readablility and productivity, you should reformat it.  You should keep your code clean for the same reason you should keep your room clean. :)

Now I have one last parting shot to make. ;) Go look at your formatting example.  Explain to me this


Code: [Select]
void DoSomething()
{

in light of this

Code: [Select]
    while ( !done ) {
:p
Title: Re: I wrote my first bit of source code!
Post by: Taristin on October 03, 2006, 08:23:46 pm
From a non-coder's perspective after reading too much of this; It seems to me that unless one is willing to rework the entire structure of the code to the format he deems correct, then one should leave it in the format that it is largely or originally in.
Seems the most logical to me...
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 03, 2006, 11:39:10 pm
But the coder should definitely adapt the code to themselves, or at least to proper design guidelines.  Basically, if you find crappy code, you should refactor it.  If you find a bug, you should fix it.  If you find a design flaw, you should redesign it.  If you find a huge function that converts uppercase to lowercase using a gigantic switch statement, you should refactor that into a function.  (I actually ran into a similar situation in the localization library in FS2 once.)  And, IMHO, if you find a section of code that looks messy and hampers readablility and productivity, you should reformat it.  You should keep your code clean for the same reason you should keep your room clean. :)
I totally agree.  A coder should always write good code (as much as possible anyway, doesn't always happen), if there is crappy code or buggy code then it should be fixed.  If there is messy code then it should be cleaned up.  If code is badly formatted then it should be reformatted so that it's easier to work with.  That seems totally obvious and I think that most everyone will tend to do that will little or no thought to the contrary.  But that isn't what we are talking about.

We are talking using formatting styles in new code which differ from the style currently used in the rest of the code base.  Changing formatting styles hurts readability unless ALL of the code also gets changed to use the new style.  It's basically the same thing is having a car which has been painted by two different people.  The car is painted blue, except for the hood which is red.  Why?  Because the person painting the hood liked the color red better.  Or it's like you handing in a group project for school, and everyone used a different font in the paper because it was their preference.  You don't mix styles, that's not only basic coding etiquette but also basic design/engineering standards.  You simply don't do it. 

I don't have a problem with with BSD/Allman or with anyone using it if that is their preference.  But you just don't go into an existing large code base, formatted with some other syle, and start using your own.  You change your style to match the style of the code that you are working with, whether that's BSD/Allman, K&R, GNU, or some strange combination of them.  THAT is a coder adapating to the code.


Now I have one last parting shot to make. ;) Go look at your formatting example.  Explain to me this

Code: [Select]
void DoSomething()
{

in light of this

Code: [Select]
    while ( !done ) {
I don't see the problem.  The top snippet is a correct function definition regardless of formatting style, and the body of the function is K&R.  K&R does not put "void DoSomething() {", that's considered wrong.  Sorry, but you'll need to take a better shot than that. ;)
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 04, 2006, 08:38:17 am
It's readable... thats the key thing... weither it's K&R or GNU thats irrealavant.  As long as your not becoming a perl programmer on us  :lol:

Interestingly enough, in my Calc III class, I saw a guy who had four windows open on his laptop working on what was obviously some sort of source code.  Turns out he's a programmer for a local company.  I asked him what language he was using and he said perl.  He said his favorite languages are Python and Ruby.  Python is more efficient, but Ruby is easier to use.  He said he thinks C++ is one of the worst languages ever made.  It's easy to use, but it takes up a lot of processing power.  C on the other hand, is not so easy to use, and can be a bit confusing, but is much more efficient and powerful.  He recommended CYGWYN as a good free compiler for C.  What do you guys think?
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on October 04, 2006, 11:14:41 am
[snip]
THAT is a coder adapating to the code.

Okay, gotcha.

Quote
I don't see the problem.  The top snippet is a correct function definition regardless of formatting style, and the body of the function is K&R.  K&R does not put "void DoSomething() {", that's considered wrong.  Sorry, but you'll need to take a better shot than that. ;)

Well, here's the thing.  The central difference between K&R and B/A is "where does the opening brace go".  K&R puts it on the same line as the control statement, whereas B/A puts it on the following line.  However many K&R advocates put function braces on the following line, as you did, which is inconsistent.

Now I've seen some die-hard K&R advocates put the function brace on the same line.  Although I disagree with the style in general, at least they're being consistent.  But I can't fathom why the rest of the K&R coders regularly break their own style that way.  I was hoping you could provide some insight into that.   How is it "considered wrong" if it's consistent with the style?
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 04, 2006, 11:31:50 am
My prof. doesn't explicitly teach K&R nor B/A, however, his examples for the code he writes appears to be consistent with B/A.  I really kinda copy him, but I also organize mine in a manner that I think is most easy to read.  I completely isolated the brackets, like such:

Code: [Select]
#include<stdio.h>
int main ()

{

        function...
        return (0);

}


That way I can say to myself, "Hey, the function starts here, idiot!"  and "The function ends here too, stupid!"  So there is no confusion.  My method "wastes" even more notepad space because I'm putting in lines with absolutely nothing in them.  Not that that'll make a difference in execution, since the compiler completely ignores spaces and such.  It just makes the code files take up more space on your hard-drive, but with 250GB hard drives as the norm, it really doesn't make that much of a difference, IMHO since it won't affect processing speed or anything, ASAIK.

Here's (http://www2.sunysuffolk.edu/lambiar/schedule.htm) my professor's class outlines.  You can see how he writes code, it seems fairly consistent with B/A.
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 04, 2006, 12:59:39 pm
But I can't fathom why the rest of the K&R coders regularly break their own style that way.  I was hoping you could provide some insight into that.   How is it "considered wrong" if it's consistent with the style?
The official/original C book did it that way.  It is subsequently considered the "official" K&R style, since they wrote it obviously.  So technically K&R dictates that you put the opening function brace on the first clear line, by itself.  The closing brace will also be on a line by itself.  And the body of the function must be indented past that point.  Those die-hard K&R advocates are actually wrong since they aren't truely following K&R rules.  They probably just got sick of all of those people who questioned the inconsistency of it and changed in order to shut them up. ;)

From the CodingStyle doc:

Quote
The other issue that always comes up in C styling is the placement of
braces.  Unlike the indent size, there are few technical reasons to
choose one placement strategy over the other, but the preferred way, as
shown to us by the prophets Kernighan and Ritchie, is to put the opening
brace last on the line, and put the closing brace first, thusly:

        if (x is true) {
                we do y
        }

However, there is one special case, namely functions: they have the
opening brace at the beginning of the next line, thus:

        int function(int x)
        {
                body of function
        }

Heretic people all over the world have claimed that this inconsistency
is ...  well ...  inconsistent, but all right-thinking people know that
(a) K&R are _right_ and (b) K&R are right.  Besides, functions are
special anyway (you can't nest them in C).

This also goes with my preferred formatting style for switch statements:
Code: [Select]
switch
{
    case SOMETHING:
    case SOMETHING_ELSE:
    ...
    break;
}
since switch statements are considered nested functions (though perhaps not technically).  So in that case you would format a switch statement the same way that you would format a function.
Title: Re: I wrote my first bit of source code!
Post by: Goober5000 on October 04, 2006, 06:45:29 pm
K.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 04, 2006, 08:10:54 pm
Hmmm, I just saw that my prof does something different than all of that.  He does something like this:

Code: [Select]

        struct CurrentList

            { COMPLEX Node[50];

               int MaxNodes;

        };


Look, he has the left bracket, then a tab, then some stuff.  Totally different that K&R and B/D as far as I can see.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 04, 2006, 08:55:53 pm
that looks a bit like the Pico format  :no:

The { shouldn't be the first thing on a line, same as "," and operators except "(".  It looks rather unnatureal.

Edit: by first thing on a line, excluding it being by itself...
Title: Re: I wrote my first bit of source code!
Post by: Flipside on October 04, 2006, 09:03:17 pm
I tend to always put curly brackets on a line of their own, simply for readability of code.
Title: Re: I wrote my first bit of source code!
Post by: Mongoose on October 05, 2006, 01:33:23 pm
My C class's professor used a style that I'm guessing was equivalent to the "fake" K&R; he put every opening bracket, including those of functions, at the end of a line.  That's generally what I've used since then, since that's how I first coded.  My C++ professor last semester used the BSD/Allman; he always made fun of my C professor (whom he was friends with) for doing things the other way. :p
Title: Re: I wrote my first bit of source code!
Post by: At on October 05, 2006, 10:32:07 pm
Code: [Select]
void DoSomething(){int loop=processed=0;bool done=false;while(!done){done=StartProcessing loop,&processed;done=(processed==MaxLimit);}}Perl style would also be writing a small kludge script to add ()'s to the function calls' arguments, so you don't have to waste time on those things except when necessary.  Every key stroke is sacred, in the heat of the moment!  Besides, ()'s are just a suggestion.

Just kidding.  I've actually done some scripting in Perl (I use it as a general system utility language.), and aside from randomly dropping ()'s from function calls, I typically write it very much like what ever C and PHP I've done, with BSD style braces...  Even though I learnt some C from the The C Language book.  (The new one has more pictures... :o )   I'm mostly self taught, except that one C++ class a few years back.

I've looked at some of the SCP code, mostly at the physics stuff.  Thank goodness it's not too C++y, or else my brain'd've melted.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 06, 2006, 07:41:36 am
That guy I mentioned does most of his programming in Ruby, which sounds like perl only because both "pearls" and "rubies" are precious stones.  It looks interesting, but I'm not particularly interested in those languages unless my future jobs requires using them for programming search engines.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 14, 2006, 09:07:45 pm
Yeah, look at this code.  I'm sure you guys are so interested in my homework.   :lol:  Whatdya guys think about the structure.  I tried to make it as easy to look at as possible, but with all the multitude if if-else statements, it didn't look possible.

Code: [Select]
//Setup
#include<stdio.h>
#include<math.h>
int main (void)

{
//Declare Variables
double TempIn, TempOut, TempK;
char   UnitIn, UnitOut;

//Print Title
printf ("This program will convert a temperature in units\n");
printf ("of Celsius (C), Kelvin (K), Fahrenheit (F) or\n");
printf ("Rankine (R), to a temperature in any of these units.\n\n");

//Input
printf ("Input Temperature:");
    scanf  ("%lf", &TempIn);
    printf ("Units to convert from (C, K, F, R):");
    fflush (stdin);
    scanf  ("%c", &UnitIn);
    printf ("Units to conver to (C, K, F, R):");
    fflush (stdin);
    scanf  ("%c", &UnitOut);


//Calculations
//Step One, Standardizing:
if (UnitIn  > 96) UnitIn  = UnitIn  - 32;
if (UnitOut > 96)   UnitOut = UnitOut - 32;

//Step Two, Convert Input to K
if (UnitIn == 'K')
{
TempK=TempIn;
}
else if (UnitIn == 'C')
{
TempK = TempIn + 273.15;
}
else if (UnitIn == 'F')

{
TempK = (TempIn - 32) / 1.8 +273.15;
}
else if (UnitIn == 'R')
{
TempK = TempIn/1.8;
}
else
{
printf ("\nUnits %c is not a valid input.\n\n", UnitIn);
return 0;
}

//Step Three: Convert from K
if (UnitOut == 'K')
{
TempOut = TempK;
}
else if (UnitOut == 'C')
{
TempOut = TempK - 273.15;
}
else if (UnitOut == 'F')
{
TempOut = (TempK * 1.8) - 459.67;
}
else if (UnitOut == 'R')
{
TempOut = TempK * 1.8;
}
else
{
printf ("\nUnits %c is not a valid input.\n\n", UnitOut);
return 0;
}

//Output
if (TempK < 0)
{
printf ("\nTemperature is less than absolute zero.  Temperature is invalid.\n\n");
return 0;
}
if (UnitIn == 'K')
{
printf ("\nA temperature of %4.2lf K"), TempIn;
}
else
{
printf ("\nA temperature of %4.2lf \xf8%c", TempIn, UnitIn);
}
if (UnitOut == 'K')
{
printf (" is equivalent to %4.2lf K", TempOut);
}
else
{
printf (" is equivalent to %4.2lf \xf8%c", TempOut, UnitOut);
}
printf ("\n\n");
return 0;

}

I did some editing that maybe makes it better to read.  Basically I just made all the comments align to the left.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 14, 2006, 10:35:05 pm
Ok I'd like to hear the opinions about comment locations :-)
Me personally I indent them to match the code.

Btw that formatting looks quite a bit like mine, just a bit tighter

I edited it in notepad  :nervous: so it might not look right... I'd like to see what other people would do it too  :)
(I'd also have it divided into about three different functions (input, calc, output) ;

Ok It's C++ and not C...
Code: [Select]
#include <stdio.h>
#include <math.h>

int main (int argc, char *argv)
{

// Shut the warnings up
argc = argc ;
argv = argv ;

//Print Title
printf ("This program will convert a temperature in units\n") ;
printf ("of Celsius (C), Kelvin (K), Fahrenheit (F) or\n") ;
printf ("Rankine (R), to a temperature in any of these units.\n\n") ;

//Input
double tempIn ;
printf ("Input Temperature:") ;
    scanf  ("%lf", &tempIn) ;

char unitIn ;
    printf ("Units to convert from (C, K, F, R):") ;
    fflush (stdin) ;
    scanf  ("%c", &unitIn) ;

char unitOut ;
    printf ("Units to conver to (C, K, F, R):") ;
    fflush (stdin) ;
    scanf  ("%c", &unitOut) ;

//Calculations
//Step One, Standardizing:
if (unitIn  > 96)
unitIn  = unitIn  - 32 ;

if (unitOut > 96)   
unitOut = unitOut - 32 ;

//Step Two, Convert Input to K
double tempK ;
double tempOut ;
switch (unitIn)
{
case 'K':
case 'k':
tempK = tempIn ;
break ;
case 'C':
case 'c':
tempK = tempIn + 273.15 ;
break ;
case 'F':
case 'f':
tempK = (tempIn - 32) / 1.8 + 273.15 ;
break ;
case 'R':
case 'r':
tempK = tempIn / 1.8 ;
default:
{
printf ("\nUnits %c is not a valid input.\n\n", unitIn) ;
return 0 ;
}
}

//Step Three: Convert from K
switch (unitOut)
{
case 'K':
case 'k':
tempOut = tempK ;
break ;
case 'C':
case 'c':
tempOut = tempK - 273.15 ;
case 'F':
case 'f':
tempOut = (tempK * 1.8) - 459.67 ;
case 'R':
case 'r':
tempOut = tempK * 1.8 ;
default:
{
printf ("\nUnits %c is not a valid input.\n\n", unitOut) ;
return 0 ;
}
}

//Output
if (tempK < 0)
{
printf ("\nTemperature is less than absolute zero.  Temperature is invalid.\n\n") ;
return 0 ;
}

print ("\nA temperature of ") ;

if (unitIn == 'K')
printf ("%4.2lf K"), tempIn ;
else
printf ("%4.2lf \xf8%c", tempIn, unitIn) ;

print (" is equivanlent to ") ;

if (unitOut == 'K')
printf ("%4.2lf K", tempOut) ;
else
printf ("%4.2lf \xf8%c", tempOut, unitOut) ;

printf ("\n\n") ;
return 0 ;
}
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 15, 2006, 06:01:07 am
Ok I'd like to hear the opinions about comment locations :-)
Me personally I indent them to match the code.
Yep, comments should be indented the same as the code they are referring to.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 08:06:10 am
Hmmm, lets see if it runs on the compiler.  BTW, I did notice you had case 'K' and case 'k', etc.  The lower case cases are not necessary since I already stadardized with:
Code: [Select]
if (UnitIn>97) UnitIn=UnitIn-32
That converts any lower case character to an upper case one.  Also, I had made it UnitIn and you wrote unitIn so they weren't incompatible, but I fixed that.

There were several errors in your code, some of them went unnoticed by the debugger.  You put print instead of printf in two seperate occasions near the bottom.  You forgot to put breaks in the second switch statement.  You put a break after the first one but not the second one.  Other than that, it looks great!  Probably alot more readable than my first code.

Code: [Select]
#include <stdio.h>
#include <math.h>

int main (int argc, char *argv)
{

// Shut the warnings up
argc = argc ;
argv = argv ;

//Print Title
printf ("This program will convert a temperature in units\n") ;
printf ("of Celsius (C), Kelvin (K), Fahrenheit (F) or\n") ;
printf ("Rankine (R), to a temperature in any of these units.\n\n") ;

//Input
double tempIn ;
printf ("Input Temperature:") ;
    scanf  ("%lf", &tempIn) ;

char UnitIn ;
    printf ("Units to convert from (C, K, F, R):") ;
    fflush (stdin) ;
    scanf  ("%c", &UnitIn) ;

char UnitOut ;
    printf ("Units to conver to (C, K, F, R):") ;
    fflush (stdin) ;
    scanf  ("%c", &UnitOut) ;

//Calculations
//Step One, Standardizing:
if (UnitIn  > 96)
UnitIn  = UnitIn  - 32 ;
if (UnitOut  > 96)
UnitOut  = UnitOut  - 32 ;

//Step Two, Convert Input to K
double tempK ;
double tempOut ;
switch (UnitIn)
{
case 'K':
tempK = tempIn ;
break ;
case 'C':
tempK = tempIn + 273.15 ;
break ;
case 'F':
tempK = (tempIn - 32) / 1.8 + 273.15 ;
break ;
case 'R':
tempK = tempIn / 1.8 ;
default:
{
printf ("\nUnits %c is not a valid input.\n\n", UnitIn) ;
return 0 ;
}
}

//Step Three: Convert from K
switch (UnitOut)
{
case 'K':
tempOut = tempK ;
break ;
case 'C':
tempOut = tempK - 273.15 ;
break;
case 'F':
tempOut = (tempK * 1.8) - 459.67 ;
break;
case 'R':
tempOut = tempK * 1.8 ;
break;
default:
{
printf ("\nUnits %c is not a valid input.\n\n", UnitOut) ;
return 0 ;
}
}

//Output
if (tempK < 0)
{
printf ("\nTemperature is less than absolute zero.  Temperature is invalid.\n\n") ;
return 0 ;
}

printf ("\nA temperature of ") ;

if (UnitIn == 'K')
printf ("%4.2lf K"), tempIn ;
else
printf ("%4.2lf \xf8%c", tempIn, UnitIn) ;

printf (" is equivanlent to ") ;

if (UnitOut == 'K')
printf ("%4.2lf K", tempOut) ;
else
printf ("%4.2lf \xf8%c", tempOut, UnitOut) ;

printf ("\n\n") ;
return 0 ;
}
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 15, 2006, 09:17:58 am
Hmmm, lets see if it runs on the compiler.  BTW, I did notice you had case 'K' and case 'k', etc.  The lower case cases are not necessary since I already stadardized with:
Code: [Select]
if (UnitIn>97) UnitIn=UnitIn-32
That converts any lower case character to an upper case one.  Also, I had made it UnitIn and you wrote unitIn so they were incompatible so I fixed that.
Umm, why not just use the standard toupper() function?  Your code is non-portable and locale specific.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 09:36:48 am
I haven't learned that one yet.  Is it understood by both C and C++ libraries?  Also, what specifically does this do?

Code: [Select]
// Shut the warnings up
argc = argc ;
argv = argv ;

Title: Re: I wrote my first bit of source code!
Post by: taylor on October 15, 2006, 09:53:58 am
I haven't learned that one yet.  Is it understood by both C and C++ libraries?
It's part of ANSI C, so it should be available in C++ too.

Also, what specifically does this do?

Code: [Select]
// Shut the warnings up
argc = argc ;
argv = argv ;
Nothing sane.  It shouldn't be there.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 10:13:00 am
Yeah, I removed it and also replaced
Code: [Select]
int main (int argc, char *argv) with
Code: [Select]
int main (void) and it works normally.

Note:  I tried looking for the toupper function here (http://www.cplusplus.com/ref/) and couldn't find it.
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 15, 2006, 11:25:32 am
Yeah, I removed it and also replaced
Code: [Select]
int main (int argc, char *argv) with
Code: [Select]
int main (void) and it works normally.
No.  That's wrong.  main() must always be "int main(int argc, char *argv[])", though "char *argv" typically works, it isn't really proper.  main() isn't some arbitrary function but a very specific one used as the program entry point by the linker.  If it isn't done correctly then your progam may not link, may not run, and will be very compiler/linker specific either way.

Note:  I tried looking for the toupper function here (http://www.cplusplus.com/ref/) and couldn't find it.
It's there (in C++, part of the standard), specified in the cctype header.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 11:54:07 am
I downloaded Microsoft Visual C++ 8.  I was using Visual C++ 6 introductory edition.  The damn thing doesn't work on 8.  When I run the code, it says "fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?"

So I put that at the top and it runs, but instead of displaying the results and leaving the screen saying "Press any key to continue" it appears to just close out of the console as soon as I enter the last input.
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 15, 2006, 02:57:51 pm
So I put that at the top and it runs, but instead of displaying the results and leaving the screen saying "Press any key to continue" it appears to just close out of the console as soon as I enter the last input.
It's a console app and, in general, when a console app is done the cmd window will close.  Such is life in a GUI environment.

You can either set the cmd window to not close when a program exits, or you can modify your code to require a key input before completing.  In the second case just run through like normal, and as the last thing in main() just wait for keyboard input (ie, a simple "Press any key...") before returning from the function.  That way you get to see all output and actually digest it before the program exits.  It's quick, easy, and it works.
Title: Re: I wrote my first bit of source code!
Post by: Turey on October 15, 2006, 03:46:31 pm
So I put that at the top and it runs, but instead of displaying the results and leaving the screen saying "Press any key to continue" it appears to just close out of the console as soon as I enter the last input.

amazingly, the following sequence will fix your problem:

Start>Run...>cmd>navigate to directory>run program
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 15, 2006, 04:04:02 pm
Hmmm, lets see if it runs on the compiler.  BTW, I did notice you had case 'K' and case 'k', etc.  The lower case cases are not necessary since I already stadardized with:
Code: [Select]
if (UnitIn>97) UnitIn=UnitIn-32
Oh thats what the -32 did... I thought it had something to do with the temperatures.  use toupper or tolower instead.

There were several errors in your code, some of them went unnoticed by the debugger.  You put print instead of printf in two seperate occasions near the bottom.  You forgot to put breaks in the second switch statement.  You put a break after the first one but not the second one.  Other than that, it looks great!  Probably alot more readable than my first code.
Well i redid it in notepad so i didn't compile it, plus i haven't written c++ in a while now, I've been using C# instead.


I haven't learned that one yet.  Is it understood by both C and C++ libraries?
It's part of ANSI C, so it should be available in C++ too.

Also, what specifically does this do?

Code: [Select]
// Shut the warnings up
argc = argc ;
argv = argv ;
Nothing sane.  It shouldn't be there.

Depends... lint or fxcop may complain about unused parameters or unused local variables.  Althought it's mostly trival.....
and yes it should be:
Code: [Select]
int main (int argc, char *argv [])
My bad, i probably should have compiled it first. I wasn't so worried about code rather formatting  :)
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 15, 2006, 04:52:38 pm
Btw what is "\xf8%c" for?
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 05:54:16 pm
Btw what is "\xf8%c" for?

It's actually just \xf8.  \x tells the compiler that the next string is a hex code for a character, f8 is the hex code for the degree sign, and that's where it stops.  %c is not part of \xf8, and I'm sure you know what %c means.
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 15, 2006, 05:59:24 pm
Depends... lint or fxcop may complain about unused parameters or unused local variables.  Althought it's mostly trival.....
Yes they might, but it doesn't mean they are correct in that.  Those two variables should also be considered const, which means you can't assign anything to them, especially to themselves.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 15, 2006, 07:03:43 pm
Well if their const then I'll retract my statement :)
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 08:32:35 pm
Okay I fixed the whole closing console problem.  I tried this toupper thing and the debugger calls it an unknown identifier.  Do I need to include a specific library?  So, with Visual C++ 8.0, it says I need to have #include <stdafx.h>.  I have no idea what that is, but apparently it replaces <stdio.h>.  I saw something similar when I was using cin and cout, so I guess they have another library that replaced <iostream.h>.  Despite the need for the extra command lines, I actually like it because it has the collapsable menus.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 15, 2006, 08:55:59 pm
put the #include <stdafx.h> at the very top
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 08:58:26 pm
put the #include <stdafx.h> at the very top


I know that!  I was merely mentioning that it replaced <stdio.h>, and it also seems to have replaced iostream.h,  though with what, I haven't figured out yet.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 15, 2006, 09:06:44 pm
Ok is this better?  :D
 It compiles and runs

tempconverter.cpp
Code: [Select]
#include <stdafx.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "tempconverter.h"

int main (int argc, char *argv[])
{
    double tempIn ;
    char   unitIn ;
    char   unitOut ;

    Input (tempIn, unitIn, unitOut) ;

    double tempOut ;
    if (!Calc (tempIn, unitIn, unitOut, tempOut))
        return 0 ; // Bad unit ;

    Output (tempIn, unitIn, tempOut, unitOut, tempOut) ;

    return 0 ;
}

//////////////////////////////////////////////////////////////////////////
// Get data from user
void Input (double &tempIn, char &unitIn, char &unitOut)
{
    //Print Title
    printf ("This program will convert a temperature in units\n") ;
    printf ("of Celsius (C), Kelvin (K), Fahrenheit (F) or\n") ;
    printf ("Rankine (R), to a temperature in any of these units.\n\n") ;

    //Input
    printf ("Input Temperature:") ;
    scanf  ("%lf", &tempIn) ;

    printf ("units to convert from (C, K, F, R):") ;
    fflush (stdin) ;
    scanf  ("%c", &unitIn) ;

    printf ("units to convert to (C, K, F, R):") ;
    fflush (stdin) ;
    scanf  ("%c", &unitOut) ;

    unitIn = toupper (unitIn) ;
    unitOut = toupper (unitOut) ;
}



//////////////////////////////////////////////////////////////////////////
// Convert from source temp to dest temp
// Returns true if successful, false if invalid temp
bool Calc (double tempIn, char unitIn, char unitOut, double &tempOut)
{
    //Step Two, Convert Input to K
    double tempK ;

    switch (unitIn)
    {
    case 'K':
        tempK = tempIn ;
        break ;
    case 'C':
        tempK = tempIn + 273.15 ;
        break ;
    case 'F':
        tempK = (tempIn - 32) / 1.8 + 273.15 ;
        break ;
    case 'R':
        tempK = tempIn / 1.8 ;
        break ;
    default:
        {
            printf ("Unit %c is not a valid input.\n\n", unitIn) ;
            return false ;
        }
    }

    //Step Three: Convert from K
    switch (unitOut)
    {
    case 'K':
        tempOut = tempK ;
        break ;
    case 'C':
        tempOut = tempK - 273.15 ;
        break;
    case 'F':
        tempOut = (tempK * 1.8) - 459.67 ;
        break;
    case 'R':
        tempOut = tempK * 1.8 ;
        break;
    default:
        {
            printf ("Unit %c is not a valid input.\n\n", unitOut) ;
            return false ;
        }
    }

    return true ;
}

//////////////////////////////////////////////////////////////////////////
// Output results
void Output (double tempIn, char unitIn, double tempOut, char unitOut, double tempK)
{
    // Check for invalid temp
    printf ("\n") ;

    if (tempK < 0)
    {
        printf ("Temperature is less than absolute zero.  Temperature is invalid.\n\n") ;
        return ;
    }

    printf ("A temperature of %4.2lf %c is equivalent to %4.2lf %c.\n\n", tempIn, unitIn, tempOut, unitOut) ;
}

tempconverter.h
Code: [Select]
void Input (double &tempIn, char &unitIn, char &unitOut) ;
bool Calc (double tempIn, char unitIn, char unitOut, double &tempOut) ;
void Output (double tempIn, char unitIn, double tempOut, char unitOut, double tempK) ;
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 09:42:04 pm
My Compiler looks at toupper and say "wtf!"   :P  *shrugs*  I dunno.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 15, 2006, 10:02:27 pm
I'm using Visual studio .net 2003.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 15, 2006, 10:19:03 pm
The free download I used from microsoft is Visual C++ 8.0 (aka 2005 Express Edition), and it includes the .NET framework.  However there seems to be more than just those changes.  Perhaps the got rid of toupper to make tighter code, maybe toupper was a source of system crashes. 

BTW, microsoft also has C#, J#, Visual Basic, and Visual Web developer for free download.  What do you guys think of these languages?  I'm guessing J# is a Microsoft knock off of Java, they use it to make windows apps. 
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 15, 2006, 10:31:28 pm
Check the help for toupper. It should tell you which header files to include (they shouldn't have changed)

Btw it needs stdlib.h not stdio.h.

Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 16, 2006, 11:46:02 am
Does anyone here use Visual C++ 8.0 with the .NET framework?  It doesn't have ANSI-C++, but instead uses CLI.  Do you guys know what they use for iostream for cin and cout and all that jazz?

Edit: Nevermind, I found (http://www.codeguru.com/forum/showthread.php?t=344569) it!  They standardized the C/C++ libraries.  It's all normal, it's just that you drop the .h from the #include line.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 16, 2006, 03:48:13 pm
The free download I used from microsoft is Visual C++ 8.0 (aka 2005 Express Edition), and it includes the .NET framework.  However there seems to be more than just those changes.  Perhaps the got rid of toupper to make tighter code, maybe toupper was a source of system crashes. 

BTW, microsoft also has C#, J#, Visual Basic, and Visual Web developer for free download.  What do you guys think of these languages?  I'm guessing J# is a Microsoft knock off of Java, they use it to make windows apps. 

Avoid J#.. VB is ok, don't know anything about VW.
I love C#
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 16, 2006, 09:15:34 pm
My dad does programming with VB.  He likes it.  I heard J# is easy to use, but is slow in execution.  Pretty much what I understand is that the easier the language, the less powerful it is.  The web developer program looks fun.  I'll definately try that out.  Hmmm, I wonder what the big difference is between the free visual studio compilers and the $300 visual studio professional compilers.
Title: Re: I wrote my first bit of source code!
Post by: Mathwiz6 on October 16, 2006, 09:17:18 pm
Get the 7 page python X and O game away from me *shivers*

Gah... the redundancy... the 8 lines for making a sprite class... the 2 pages devoted to AI... the 2 pages devoted to making an endgame message...

Better than my friend did in Javascript though... 8 pages, seperate object classes for every potential X or O.. and no AI :D
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 16, 2006, 11:57:30 pm
If you want to do java... do it the right way with Sun's Java... Just don't expect to do great fast gui with it, it's great for console stuff.

Now I know a lot of people hate VB.. the newer VB# is better, since it's more object based for one thing.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 21, 2006, 04:39:14 pm
Okay, I made a new program for my next assignment, and I found some new information.  First the program:
Code: [Select]
//setup
#include<cstdio>
#include<cmath>
int main(void)
{

//declare variables
double DataIn, Average, Sum;
int    NGrades, Value;

//print title
printf ("Program \x22");
printf ("Average\x22 \n\n");
printf ("This program calculates the average of an arbitrary number\n");
printf ("of grades.\n\n");
printf ("After all the grades have been entered, any negative number\n");
printf ("is entered, and the averaging is performed.\n\n");

//get input
NGrades = 0;
Sum = 0.0;
Value = 0;

while (Value == 0)
{
scanf ("%lf", &DataIn);
if (DataIn > 0)
{
Value = 0;
Sum = DataIn + Sum;
++NGrades;
}
else (++Value);
}

//calculate
Average = Sum / NGrades;

//output data
switch (NGrades)
{
case 0:
printf ("\nNo valid grades have been entered.\n\n");
printf ("An average cannot be computed.");
break;
case 1:
printf ("\nThere is only one grade whose value is %4.2lf.", Average);
break;
default:
printf ("\nThere are %d grades, with an average of %4.2lf.", NGrades, Average);
}
printf ("\n\n");
return 0;
}

This one is much shorter, but it took me forever to figure out how to write the while loop correctly.  I also learned more about Visual C++ 8, aka VC++ 2005.  The only real difference between the free version and the $300 version, so far as I can tell, is that the free version doesn't have the ANSI-C/C++ libraries.  That's okay, because the CLI libraries are for the most part identical, you just have to remember to use iostream and not iostream.h and cmath instead of math.h, etc.  Also, for iostream you have to add the line
Code: [Select]
using namespace std; otherwise you cin's and cout's won't work.  I also figured out why the consoles were always closing after executing instead of having that "Press any key to continue" statement at the end.  That was because I was pressing F5 which runs the "real program" instead of CTRL-F5 which runs the "troubleshooting program" which does have that statement at the end.  The same thing happens in my studen VC++ 6.0, so everything's cool now.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 21, 2006, 06:41:11 pm
You should be able to do
Code: [Select]
std::cout <<
std::cin >>


Also what happens if the first grade entered was a -1?   :drevil:
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 21, 2006, 08:11:11 pm
You should be able to do
Code: [Select]
std::cout <<
std::cin >>


Also what happens if the first grade entered was a -1?   :drevil:

It's easier just to put "using namespace std;" in the header and go on like normal, I think.  If you put -1 as the only grade, then case 0 of the switch is executed.  If you put one valid grade, and then a negative number, case 1 is executed.  If you put in more than one valid grade, and then a negative number, then the default is executed.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 21, 2006, 08:51:09 pm
Personally thats the way I do it to... although you'd get a few purists complaing....

If it looks like it does... -1 will leave NGrades to 0 and you'll never get as far as the switch statement, you'd get an exception occuring before that. (Hint remember your math  :) )
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 22, 2006, 07:40:09 am
Personally thats the way I do it to... although you'd get a few purists complaing....

If it looks like it does... -1 will leave NGrades to 0 and you'll never get as far as the switch statement, you'd get an exception occuring before that. (Hint remember your math  :) )

What kind of compiler are you using?  It doesn't do that to me.  If you look at my while loop, notice that it has an if-else statement embedded in it.  (Figuring out how to make this work took me a day and a half!)  What exits the loop is if you can get the integer called "Value" to be greater than 0.  Notice in the if else statement, it does the math if and only if the value entered for DataIn is greater than zero (I just realized it should be >=0), if DataIn is not greater than zero, then the else statement is executed, and no math is performed.  What the else statement does is increase value by one, making value equal to one.  This breaks the loop.  Simultaneously, since no math was performed, NGrades does not increase and remains zero.  So what happens is if the first thing you enter is a negative number, no math is performed, it exits the loop, and case 0 of the switch is executed, where it says

"No valid grades have been entered.

An average cannot be computed."

BTW, I just found out another trick so I don't have to use the hex code for ascii characters.  (Why didn't my prof. tell us about this earlier?)  So here's my new finalized code.
Code: [Select]
//setup
#include<cstdio>
#include<cmath>
int main(void)
{

//declare variables
double DataIn, Average, Sum;
int    NGrades, Value;

//print title
printf ("Program \"Average\" \n\n");
printf ("This program calculates the average of an arbitrary number\n");
printf ("of grades.\n\n");
printf ("After all the grades have been entered, any negative number\n");
printf ("is entered, and the averaging is performed.\n\n");

//get input
NGrades = 0;
Sum = 0.0;
Value = 0;

while (Value == 0)
{
scanf ("%lf", &DataIn);
if (DataIn >= 0)
{
Value = 0;
Sum = DataIn + Sum;
++NGrades;
}
else (++Value);
}

//calculate
Average = Sum / NGrades;

//output data
switch (NGrades)
{
case 0:
printf ("\nNo valid grades have been entered.\n\n");
printf ("An average cannot be computed.");
break;
case 1:
printf ("\nThere is only one grade whose value is %4.2lf.", Average);
break;
default:
printf ("\nThere are %d grades, with an average of %4.2lf.", NGrades, Average);
}
printf ("\n\n");
return 0;
}
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 22, 2006, 04:12:36 pm
Ok theres something funky going on here....

NGrades is set to 0
and Average = Sum / NGrades works correctly  :confused:

It should throw a divide by zero error.
Quote
Division by 0 in either a division or a modulus expression is undefined and causes a run-time error. Therefore, the following expressions generate undefined, erroneous results:
i % 0
f / 0.0
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 22, 2006, 05:08:40 pm
Ok theres something funky going on here....

NGrades is set to 0
and Average = Sum / NGrades works correctly  :confused:

It should throw a divide by zero error.
Quote
Division by 0 in either a division or a modulus expression is undefined and causes a run-time error. Therefore, the following expressions generate undefined, erroneous results:
i % 0
f / 0.0

Hmmm, your right, but it doesn't cause an error when I run the program.  Perhaps it just sees the error, ignores it, then moves on.  However, it won't see the error when it compiles the program, because NGrades is unknown until DataIn is entered.  Anyway, it works as is, the question I guess is why, but I fixed it regardless.  Here it is.

Code: [Select]
#include<iostream>
using namespace std;
#include<cmath>
int main(void)
{

//declare variables
double DataIn, Average, Sum;
int    NGrades, Value;

//print title
cout << "Program \x22";
cout << "Average\x22 \n\n";
cout << "This program calculates the average of an arbitrary number\n";
cout << "of grades.\n\n";
cout << "After all the grades have been entered, any negative number\n";
cout << "is entered, and the averaging is performed.\n\n";
//get input
NGrades = 0;
Sum = 0.0;
Value = 0;

while (Value == 0)
{
cin >> DataIn;
if (DataIn >= 0)
{
Value = 0;
Sum = DataIn + Sum;
++NGrades;
}
else (++Value);
}

//calculate
if (NGrades >0)
Average = Sum / NGrades;

//output data
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.\n\n";
cout << "An average cannot be computed.";
break;
case 1:
cout << "\nThere is only one grade whose value is " << Average << ".";
break;
default:
cout << "\nThere are " << NGrades << " grades, with an average of " << Average << ".";

}

cout << "\n\n";
return 0;
}
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 22, 2006, 05:15:14 pm
That'll fix the problem  ;)

Actually NGrades is known... you set it to zero right after //get input
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 22, 2006, 05:35:18 pm
That'll fix the problem  ;)

Actually NGrades is known... you set it to zero right after //get input

Yeah, but why did I not get a runtime error before?  I would run the program, enter -1 as my first grade, and it would execute case 0.  I would not get a runtime error.  Why is that?  I use VC++6 and 8, and it runs fine without the runtime error on both of them.  Do you get one with yours?  What kind of compiler do you use?
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on October 22, 2006, 06:54:19 pm
.NET 2003

Ahhh take a look at the value of Average after doing the division.... it's NaN  (Not a Number)
Title: Re: I wrote my first bit of source code!
Post by: taylor on October 22, 2006, 08:26:58 pm
Yeah, but why did I not get a runtime error before?  I would run the program, enter -1 as my first grade, and it would execute case 0.  I would not get a runtime error.  Why is that?
The rules for this are slightly different because it's float-point based math, not integer based.

Floating-point math should give you a predictable result (ie, NaN or INF), but probably not generate an error (this can be compiler/CPU dependent though).  The result can later generate a runtime error if you act upon that result however (ie, if "Average" is NaN, then it could segfault if you then do "Sum /= Average").  So it's still a good idea to check for and/or prevent div-by-0 errors, since otherwise you'll probably need to check for NaN at some point to prevent crashes that may be a little more difficult to track down.

In integer math you should get an instant runtime error (some CPUs can actually handle the error, giving 0 as the result).


It may only take a matter of seconds to fix a div-by-0 related crash since it happens relatively instantly.  With something like NaN errors though, I've spent (on several occasions) the better part of a day tracing through the FSO code looking for the cause of a NaN related crash.  Because NaN related problems can happen much later in the program they are really something that you want to avoid.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on October 23, 2006, 09:03:06 am
Hmm, NGrades is an integer, but since Sum is a double and is the sum of all DataIn, which is also double, then it performs float point math, as apposed to integer math.  Makes sense, makes sense.
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on November 02, 2006, 08:38:29 pm
Er, I'm having problems.   :nervous:  I e-mailed my professor, but he hasn't responded to me.  I thought perhaps I can use the expertise here at the HLP to help me. ;)  So, for this assignment, we got to make this program based off of our mid-term exam.  No biggie, it's kinda like the last one where the average of a bunch of numbers is performed.  This time, however, the user inputs letter grades, but only the following letter grades: A, C, and F.  A is equivalent to 95, C is 75, and F is 50.  Once the user inputs any letter that is not an a, c, or an f, the average of all the grades entered is performed.  You can do this all with one nice main function, which we did for the mid-term, but for this assignment our professor wants us to make the title and the part where it converts a letter to it's numerical equivalent part of separate functions outside the main, since we're doing user defined functions now.  The title function is a piece of cake, but the other one is killing me.  I can't get it to work the way I want it to.  What I want it to do, is take a character, that I called DataIn, and convert it to a double number, which I call Value.  No matter what I do, I can't make a function do that.  Here's what I got so far (that doesn't work).

Code: [Select]
//Mid-Term Exam Revisited
#include<iostream.h>
void Title (void);
double Convert (char DataIn);

int main (void)
{
double Sum = 0.0, Average, Value;
char   DataIn;
int    NGrades = 0, close = 0;

Title (); //Print Title

//Prompt and get Data
while (close == 0)
{


cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
if (DataIn >= 97)
DataIn = DataIn - 32;
Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
else ++close;

}


//Calculate
if (NGrades > 0)
Average = Sum / NGrades;

//Output Results
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.";
break;
case 1:
cout << "\nOnly one grade has been entered whose value is "<< Sum;
break;
default:
cout << "\nThe average of " << NGrades << " grades is " << Average;
}

cout << "\n\n";
return 0;
}

void Title (void)
{
cout << "This program computes averages using three letter grades.\n\n";
  cout << "A = 95, C = 75, F = 50. Any other letter stops data entry.\n\n";
}
double Value (char DataIn)
{
double Value = 0.0;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
return (Value);
  }

Now, I know that the switch statement in the Value function works, and that the while statement in the main function works.  This I confirmed by getting rid of the Value function and placing it's switch statement directly in the spot where it's supposed to be within the while statement of the main function.  When I do that the program works.  It looks like this:

Code: [Select]
//Mid-Term Exam Revisited
#include<iostream.h>
void Title (void);

int main (void)
{
double Sum = 0.0, Average, Value;
char   DataIn;
int    NGrades = 0, close = 0;

Title (); //Print Title

//Prompt and get Data
while (close == 0)
{


cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
if (DataIn >= 97)
DataIn = DataIn - 32;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
else ++close;

}


//Calculate
if (NGrades > 0)
Average = Sum / NGrades;

//Output Results
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.";
break;
case 1:
cout << "\nOnly one grade has been entered whose value is "<< Sum;
break;
default:
cout << "\nThe average of " << NGrades << " grades is " << Average;
}

cout << "\n\n";
return 0;
}

void Title (void)
{
cout << "This program computes averages using three letter grades.\n\n";
  cout << "A = 95, C = 75, F = 50. Any other letter stops data entry.\n\n";
}

Can anybody point to me where I'm going wrong?   :confused:
Title: Re: I wrote my first bit of source code!
Post by: AdmiralRalwood on November 02, 2006, 10:02:55 pm
Granted I'm no expert, but I notice you have
Code: [Select]
double Value = 0.0;in the first version but not in the second. Since "double Value" is the exact same name as your function, perhaps that's the cause of your problem?
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on November 02, 2006, 10:04:27 pm
Oh I think I see the problem without even compiling it  :)

Code: [Select]
Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}

Your forgetting to assign Value the result from Convert
Code: [Select]
Value = Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on November 02, 2006, 10:07:12 pm
BTW replace int close = 0 with bool close = false

replace while (close == 0) with while (!close)

and finally

replace else close++ with else close = true

close is an on/off toggle flag.. better to use bool for those.
Title: Re: I wrote my first bit of source code!
Post by: AdmiralRalwood on November 02, 2006, 10:07:45 pm
...I can't belive I didn't notice that. Should've just kept lurking, I guess. :P
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on November 02, 2006, 10:10:23 pm
Granted I'm no expert, but I notice you have
Code: [Select]
double Value = 0.0;in the first version but not in the second. Since "double Value" is the exact same name as your function, perhaps that's the cause of your problem?

Those two double Value 's are totally different variables, they occur on different scopes.
Title: Re: I wrote my first bit of source code!
Post by: StratComm on November 02, 2006, 10:30:03 pm
Any good compiler will see the difference between "Value" and "Value(...)" though I'm a little surprised you didn't see a warning.  Scope actually has nothing to do with it in this case, as there's a very real risk of infinite recursion if you aren't careful with the way that's written.

And I think convention is generally to not use drop caps for variables and only use it for functions, but that's just convention. 

BTW replace int close = 0 with bool close = false

replace while (close == 0) with while (!close)

and finally

replace else close++ with else close = true

close is an on/off toggle flag.. better to use bool for those.

Bools are so overrated.  They don't save any memory and their underlying representation is usually an int anyway.  They're good for reducing confusion but functionally is exactly the same.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on November 02, 2006, 10:38:30 pm
Wait a moment.....
shouldn't the function Value be named Convert instead?
Code: [Select]
double Value (char DataIn)
{
double Value = 0.0;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
return (Value);
  }

Compared with the predefintion and how you used it in the main function
Code: [Select]
double Convert (char DataIn);
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on November 02, 2006, 10:40:21 pm
Bools are so overrated.  They don't save any memory and their underlying representation is usually an int anyway.  They're good for reducing confusion but functionally is exactly the same.

For size differences I agree, no difference.  But for clarity they can do a lot.  Compared to close++ and close = true.
Title: Re: I wrote my first bit of source code!
Post by: AdmiralRalwood on November 02, 2006, 10:41:09 pm
...I can't believe I didn't notice that one, either. Definately should've just kept lurking.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on November 02, 2006, 10:45:54 pm
Thats where I was going with the scope issues.  At the time I didn't even see Value () [my mind must have thought Convert ()]
Title: Re: I wrote my first bit of source code!
Post by: Freespace Freak on November 03, 2006, 07:32:34 am
Wait a moment.....
shouldn't the function Value be named Convert instead?

Wait a moment.....
shouldn't the function Value be named Convert instead?

Yes.   :nervous:  I was going in between naming it Value and Convert, so you would see Value (DataIn) in that spot instead of Convert (DataIn).  When I posted, I was going from naming the function Value to Convert, and I didn't realize that the function name itself hadn't been changed.  My bad.  But yes, you fixed it Scoob.  :yes:  You get Scooby snacks!   :P  Just putting in the Value = Convert (DataIn) fixed it.  The whole bool stuff works, and I understand boolean algebra, but I can't remember if we actually covered that in class.  However, the other method works just as well.  I'll use my method, until I know it's okay for me to use bool.  Here's my finalized and working code:
Code: [Select]
//Mid-Term Exam Revisited
#include<iostream.h>
void Title (void);
double Convert (char DataIn);

int main (void)
{
double Sum = 0.0, Average, Value;
char   DataIn;
int    NGrades = 0, close = 0;

Title (); //Print Title

//Prompt and get Data
while (close == 0)
{
cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
Value = Convert (DataIn);
if (Value > 0)
{
Sum = Sum + Value;
++NGrades;
}
else ++close;
}


//Calculate
if (NGrades > 0)
Average = Sum / NGrades;

//Output Results
switch (NGrades)
{
case 0:
cout << "\nNo valid grades have been entered.";
break;
case 1:
cout << "\nOnly one grade has been entered whose value is "<< Sum;
break;
default:
cout << "\nThe average of " << NGrades << " grades is " << Average;
}

cout << "\n\n";
return 0;
}

void Title (void)
{
cout << "This program computes averages using three letter grades.\n\n";
  cout << "A = 95, C = 75, F = 50. Any other letter stops data entry.\n\n";
}
double Convert (char DataIn)
{
double Value;
if (DataIn >= 97)
DataIn = DataIn - 32;
switch (DataIn)
{
    case 'A':
      Value = 95.0;
break;
    case 'C':
      Value = 75.0;
break;
    case 'F':
      Value = 50.0;
break;
    default:
      Value = -1;
}
 
return (Value);
  }

This same program was on the Mid-term, except we did it all in the main function.  What my professor did for the while loop required the input prompt to be placed in the code twice, once before the while loop, and one inside the while loop.  Like this:
Code: [Select]
        cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
Value = Convert (DataIn);

        while (Value > 1)
{
                Sum = Sum + Value;
++NGrades;

cout <<  "Input Letter Grade: ";
cin   >>  DataIn;
Value = Convert (DataIn);
}
That works, but, not to criticize my own professor, it looks sloppy.  I think putting everything within the loop without having to put any statements in front of it to make it work is a better way of doing things.
Title: Re: I wrote my first bit of source code!
Post by: Scooby_Doo on November 03, 2006, 03:30:08 pm
I guess the best suggestions for loops is put only what absolutely has to go in a loop and leave everything else out.  A slightly less chance of additional errors and more optimized  :)