When are functions needed and where should they live?

Pages: 12
closed account (Ezyq4iN6)
I am looking for some rules, explained in beginner terms, about how to use functions effectively. I know what a function is, and I know that it can be used to improve readability, reduce repetitive code, and even placed in .h/.cpp file combos to use in future programs.

But my question is what is the test to determine exactly when any of those should be done?

For example, with the .h/.cpp file combo, I obviously don't want to have 100+ files, each with one function. However, if I combine some like functions, for example math ones, I may end up only using a few formulas in huge list and that feels like a waste to include that.

And for the "when to use" part, consider the following code with a distance formula. I know it's a simple math formula, but it could be far more complex. Sure, it can be done with one line, but what the long math formula is doing might be confusing at first if someone doesn't know what's going on (bad or missing comments, etc.) Turning it into a function seems like a great idea, but it also adds a ton of lines if I want to make it more readable. I like the second option because the main code part makes more sense, but prefer the first because it's less lines of code to sift through, even though I may know the function works, it's still there occupying space.

So I hope you can see my dilemma. As a beginner, I strongly fear developing bad practices that will cost me a job later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  // In main, only one line, but long.
  main()
  {
    // Finding the distance between two points.
    double distance = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  }

  // In a function, more lines, but broken up to make steps more readable.
  double find_distance(double x1, double y1, double x2, double y2)
  main()
  {
    double distance = find_distance(x1, y1, x2, y2);
  }
  double find_distance(double x1, double y1, double x2, double y2)
  {
    double x_diff = x2 - x1;
    double y_diff = y2 - y1;
    double x_diff_squared = x_diff * x_diff;
    double y_diff_squared = y_diff * y_diff;
    return sqrt(x_diff_squared + y_diff_squared);
  }


However, if I combine some like functions, for example math ones, I may end up only using a few formulas in huge list and that feels like a waste to include that.

I don't think you should worry too much about this. Compilers are terribly fast. #include <iostream> adds 30 000 lines (700 KB) of code for me with GCC 7.3 and compiling still takes less than half a second.

And for the "when to use" part, consider the following code with a distance formula. I know it's a simple math formula, but it could be far more complex. Sure, it can be done with one line, but what the long math formula is doing might be confusing at first if someone doesn't know what's going on (bad or missing comments, etc.) Turning it into a function seems like a great idea, but it also adds a ton of lines if I want to make it more readable. I like the second option because the main code part makes more sense, but prefer the first because it's less lines of code to sift through, even though I may know the function works, it's still there occupying space.

I think it's a good idea to put the distance computation into its own function. Not necessarily so much for the sake of readability (it's relatively easy to see what is going on if you know how a distance calculation look like) but more for avoiding mistakes. It's much easier to make sure the calculation is correct if you have it in one place instead of repeated multiple times throughout the code. You can even write a program that tests the distance function with various inputs and see if it returns the expected output. Such tests are much harder to do if the code you want to test is not separated into its own function.

The choice of splitting the computation over multiple lines is somewhat independent of whether or not you choose to put it into it's own function. I'm not sure I prefer the split up version from a readability point of view but it might be better for other reasons (e.g. performance). Personally I would probably have written it something like this ...

1
2
3
double dx = x2 - x1;
double dy = y2 - y1;
return sqrt(dx * dx + dy * dy);
dx = Δx (delta x), dy = Δy (delta y)

... because I don't think the diff_squared variables adds anything, and leaving them out makes it a bit shorter.


Another alternative is to create a square function and use it in the distance calculation.

1
2
3
4
5
6
7
8
9
double square(double value)
{
	return value * value;
}

double distance(double x1, double y1, double x2, double y2)
{
	return sqrt(square(x2 - x1) + square(y2 - y1));
}

Now you have two functions but both of them are short and easy to read.
Last edited on
math is almost an exception.
most of your functions will live inside classes. a few may be stand-alone, and that is more often true when they do math that could be useful in any of many classes, but the bulk of your code will be in classes in c++. That will, when you study it, tell you how to arrange the header files and so on.

people won't generally sift through your code at the line by line level anyway. They will read the prototype for the function, which will, because you are a good programmer, have comments on what it does / how to use it /etc. That is all they care about, really --- what does it do, and how do I call it. If its bugged up, they will have to dig into it, or if they want it to do something else (copy and modify coding is a big time saver) but not just to use it.

code bloat is an issue. Being super explicit tends to create slower code that is annoying to read. Give your peers some credit, they can handle the long line you wrote in main if it has a comment saying what it is, they will understand. There is a balance between 1-2 line cryptic code that no one can unravel how it works and 20 lines of bloat that treats the reader like a 3 year old. Find the balance (comes with practice). Youll get there.


this is fine.

double find_distance(double x1, double y1, double x2, double y2)
{
return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); //not that complex.
}

Another alternative is to create a square function and use it in the distance calculation.


I think most people that do a ton of math have an efficient integer powers routine coded up because pow() is so slow.
Last edited on
closed account (Ezyq4iN6)
@Peter87
I guess you're right about the fast computer preventing crazy long compile time, but what about the file size bloating and any effects to execution speed? Is there any way to trim that down by only including certain functions from the file?

Also, is it better to have the .h for function prototypes and .cpp for definitions, or should I put everything in one or the other?

I like your modification to the distance function, and I'll use that for mine too if you don't mind. Is the one with the square function, or the one with all in one function usually preferred?

Also, what you said in your second paragraph, about avoiding mistakes, better describes the reasoning for my question. I want to write the program so that it is harder to make mistakes. Since I have never written a large program, and only giant main() programs with occasionally a few includes based on advice from here and other sites, I kind of wanted to know if it was the accepted practice to wrap everything up into classes and functions, rather than having a bunch of code in main.

@jonnin
I have only had basic instructions on classes, but I was never really taught how to use classes in the way I see in most code, where they do most of the work.

Speaking of comments, do they only go over the prototype of the function? Also, how much detail do they need to have? If you could give me a link or an example with this function that would be great. I usually just have something like // Calculates distance over both the prototype and the function.

I guess I try to put a lot of parts to everything since I know other people's code is hard for me to read. Also, I don't know what skill levels will be reading my code, I mean probably all higher than me to be sure, but I don't want to confuse anyone since my code may be inefficient and confusing to better programmers.
compilers are scary smart now. they only include what you need, and they shift code to be pretty efficient even if you wrote it without trying to minimize the work done. Also, your computer can do billions of operations per second. it takes a pretty large problem to notice minor inefficiency.


you want prototypes in h and body in cpp 'generally'. templates have their own rules (all goes in header) and there are exceptions (very small projects all in .cpp is not uncommon).

its not good practice to have a lot in main, usually main kicks off the program and maybe has a small # of variables, not much else.

comments go where your style guidelines (your company will tell you these when you land a job) tell you AND where your common sense tells you. If you do something weird, like using tan() to compute slope of a line, you comment what you did so as not to confuse the reader.

professional comments get kind of wordy :)

/*
function find_distance
this function returns the Euclidian distance in the X/Y plane.
inputs:
x1 is the x coordinate of the first point
x2 is the x coordinate of the second point
y1 is the y coordinate of the first point
y2 is the y coordinate of the second point
outputs:
returns the distance between x and y

History
20190226 opisop cleanup, added 'square' function dependency
20181225 opisop initial code

*/

just assume everyone else is at your own level. If you were reading it and feel confused, so would someone else, and if you were reading it and find it easy to follow, so would someone else. Its all you can really do, is your best, you know?
Is the one with the square function, or the one with all in one function usually preferred?

That's up to you. Just pick one and go with it. Some advice: Don't paralyze yourself over little details like this, they often don't matter. If the square function was some huge, complicated function with lots of branches, then I would say it's good to factor it out into its own equation, but in this case, it's really just up to you. Like Jonnin said, once you write more code you'll get the hang of what looks nice and readable, and what doesn't.

Here's some tips for when to use functions:
- When you spot duplicate code (or mostly duplicate code that only differs by a few values).
- When you have really long functions.
- When you have multi-line logic that you want make sure it kept together.

If you're worried about efficiency and stuff like take, I suggest looking up data structure and algorithms. This is where performance can actually matter. (If you're in a college, look if they offer classes like that, otherwise look it up with online resources or PDFs.) But again, don't paralyze yourself and not write anything because you're afraid of how something might be inefficient. An extra function push/pop is not going to make or break your program, don't worry about that specifically.

Also, is it better to have the .h for function prototypes and .cpp for definitions, or should I put everything in one or the other?

Normally, the function prototypes (that you want to be usable by other files) go in the .h, and the definitions go in the .cpp.

I kind of wanted to know if it was the accepted practice to wrap everything up into classes and functions, rather than having a bunch of code in main.
Classes are a whole other beast, but generally I'd say a function shouldn't span more than ~50-100 lines of code. This is just a heuristic though, I certainly have tons of functions that are more than that.

Some functions might just be a line long, but the point of them is to be a "human readable" piece of reusable logic.
e.g.
1
2
3
4
5
/// t must be in range [0, 1]
byte interpolation(byte a, byte b, double t)
{
    return std::round( (1.0 - t) * a + t * b );
}


Speaking of comments, do they only go over the prototype of the function?

Comments go wherever you want :)
One use of comments is to spell out the intention of what the code should be doing.
Comments are to provide context to someone reading your code to explain what's happening, for times when the code itself might not be clear.
When comments are put above a function, it's usually to give a summary of what that function does, and any cautionary notes about the function.

// Calculates distance over both the prototype and the function.

I don't understand this comment. "over both the prototype and the function"? You're using C++ syntax terms while explaining the logic of a function.
I would just saying something like,
"Calculates the distance between two (x, y) points". Done.

Here's an example of a comment on a random piece of code I have. I probably put a comment there because it might not be immediately obvious of what the for loop is doing. It can help the reader not get lost in the code.
1
2
3
4
5
6
7
8
    // initialize template map to be completely white
    for (size_t i = 0; i < map_specs.pixels.size(); i += 4)
    {
        map_specs.pixels[i+0] = 255;
        map_specs.pixels[i+1] = 255;
        map_specs.pixels[i+2] = 255;
        map_specs.pixels[i+3] = 255;
    }


If I have parts of a function that I don't think are worth it to factor out into their own functions, I might do something like this, to denote a "section" of the process.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    //
    // 1. Make image (cone)
    //
    
    Point center(width/2, height/2);
    double factor = (width/2) * std::sqrt(2);   
    for (unsigned y = 0; y < height; y++)
    for (unsigned x = 0; x < width; x++)
    {
        double d = distance(Point(x, y), center);
        d = d / factor;
        image.pixels[4 * width * y + 4 * x] = 255 * d;
    }

    //
    // 2. Do something else
    //

    // ... 
Last edited on
closed account (Ezyq4iN6)
@jonin
I have read about templates, but I don't know much about them. All of my function are really standard with int, double, etc. passed and returned, so I guess the .h/.cpp combo will work for now.

Also, I'll have to learn how to get things out of main. I'm so used to just sticking all in main that it will probably take a while until I can figure out how to do that, but I definitely want to since it is standard.

Wow, that is a long comment, but it makes sense. That looks a lot better than what they make me do in classes, which is comment every line like the following:
1
2
3
4
5
6
  int x; // x-coordinate for car center.
  int y; // y-coordinate for car center.
  // Start of main program
  int main()
  ... etc.


I really hope if I get a job as a programmer I don't have to comment every line. :/

Thanks again for all of your help!

@Ganado
Sorry about my attention to detail, but in my internship I saw such a huge gap between what we learn in class and what a 1st year programmer/software engineer is expected to know that I'm always nervous I won't do things right.

That's good advice about putting multi-line logic together. I guess a function doesn't always have to be just to do one thing then, but rather something to take a bunch of junk out of main, right?

I think we have a class that focuses on algorithms, so I'll look into that. Also, I will read up on what I can find on the web for free too.

Your comment suggestions are helpful, I'll try to remember them. Also, your example is much cleaner than mine.

I see that size_t a lot. Is it just a positive integer, and can it be used interchangeably with integers? I ask because I always used int in for loops.

That last part I've never seen before, but it looks interesting. I'll have to try segmenting my code like that into sections.

Thanks for your help too!
I really hope if I get a job as a programmer I don't have to comment every line. :/

Absolutely not, no job is going to *require* you to comment every line. In fact, that would be very unproductive. Summarize the essence of the code instead, and comment things that you think need clarification.

One rule of thumb is: "If I were to take long break and come back to this code a month, or a year from now, would I know what it's doing?"

For instance, your comment of "Start of main program" is not needed. Anyone working in C++ will know that the main function is the "starting point" of the program.
Also, sometimes it makes more sense to make variable names more descriptive instead of having comments.
For example, instead of
1
2
  int x; // x-coordinate for car center.
  int y; // y-coordinate for car center. 

you might just have
1
2
  int car_center_x;
  int car_center_y;


I saw such a huge gap between what we learn in class and what a 1st year programmer/software engineer is expected to know that I'm always nervous I won't do things right.
Completely understandable, but I really wouldn't expect a first-year programmer to be comfortable with a large project unless they were really dedicated. It takes time -- make a bunch of programs. Practice makes perfect. Just like drawing, or learning a song, or playing a sport.

I guess a function doesn't always have to be just to do one thing then, but rather something to take a bunch of junk out of main, right?

Well, not exactly. Yes, a function should do "one thing", though that "thing" can be a broad act that can be further divided into other tasks. Don't just randomly segment the code into functions. You should together group logic that belongs together.

When thinking of functions, think verbs. Make, get, add, run, jump, split, move, stop, etc. What is happening? What is this part of the code doing?

Here's some links that might be interesting:
https://softwareengineering.stackexchange.com/questions/308108/when-is-it-appropriate-to-make-a-separate-function-when-there-will-only-ever-be
https://softwareengineering.stackexchange.com/questions/195989/is-it-ok-to-split-long-functions-and-methods-into-smaller-ones-even-though-they
https://www.reddit.com/r/readablecode/comments/1d0n7o/is_it_ok_to_split_long_functions_and_methods_into/

For example, when you're making a program, try to tell yourself (out loud!) what it does, in words. Or perhaps, how it does it.
some reddit user wrote:
I totally agree with what MichaelT is saying on [StackOverflow].

"If, when describing the activity of the code to another programmer you use the word 'and', the method needs to be split into at least one more part."

Seems like a nice rule of thumb as well.


I see that size_t a lot. Is it just a positive integer, and can it be used interchangeably with integers? I ask because I always used int in for loops.

It makes the compiler shut up about warnings between comparing unsigned and signed integers, because vector.size() returns a size_t (which is an unsigned type). In general, prefer signed types, because unsigned types can mask some logic errors. This isn't too critical though, don't worry about it at your stage.

BTW: Always compile with warnings (even if some of them are annoying, 99% of them are accurate). Look up "compile with warnings [your compiler name]" (in g++ for example, use -Wall).

Last edited on
Also, is it better to have the .h for function prototypes and .cpp for definitions, or should I put everything in one or the other?


I name c++ header files as *.hpp. It's just a convention, *.h is for C header files.


If you use good names for your variables and function names, the code should tell a story of what it does. Use comments for something really does need explanation because it is unusual. Comments at the start of functions are good. There are documentation programs like doxygen which rely on comments of a particular format.
closed account (Ezyq4iN6)
@Ganado

That's good advice about comments and variable names. I like the idea of descriptive variable names, but was always hesitant because of something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int car_center_x = 100;
int car_center_y = 100;
int goal_center_x = 100;
int goal_center_y = 100;

double distance = find_distance(car_center_x, car_center_y, goal_center_x, goal_center_y);

// versus

int cx = 100;
int cy = 100;
int gx = 100;
int gy = 100;

double dist = find_dist(cx, cy, gx, gy);


The top version is much more understandable, but the bottom version is less cluttered. I guess sometimes I see longer lines, or functions/objects that take multiple lines with parameters and I'm worried it will "look bad" or add too many lines to the code.

Those links are helpful, thanks. So what you're saying is that you can split up the functions like the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

main()
{
  run_program()
  return 0;
}

run_program()
{
  init();
  while (!quit)
  {
    logic();
    draw();
  }
}

logic()
{
  read_controls();
  rotate_car();
  move_car();
  if (is_car_at_goal())
    quit = true;
}

draw()
{
  draw_car();
  draw_goal();
}

// The alternative that I know, which is the way I learned in early programming, is as follows:

main()
{
  init();
  while (!quit)
  {
    read_controls();
    rotate_car();
    move_car();
    if (is_car_at_goal())
      quit = true;
    draw_car();
    draw_goal();
  }


On one of the links I read that someone labeled this "sequential coupling" and said that it was usually bad, but I really don't see another way it could be done except for listing all of the base functions in a row (second example), which would seem like doing the same thing, only more cluttered. It also goes with what you are saying about if you use the word "and" in a function description, you need to split it up. But I don't understand how you would structure a program without having some functions that had multiple purposes (like logic and draw), or a sequential list of all of the base functions, which also seems like it's probably not the best way.

I think I have seen the warning about unsigned/signed comparison before. I usually put "unsigned int" instead of "int" to make it go away. I guess I never figured about the unsigned errors when doing this.

@TheIdeasMan
I'll try to remember to name my .h files .hpp from now on. I guess a lot of the examples I see and includes have .h, so I'm so used to that.

Other than functions, what else might benefit from a comment?
The top version is much more understandable, but the bottom version is less cluttered. I guess sometimes I see longer lines, or functions/objects that take multiple lines with parameters and I'm worried it will "look bad" or add too many lines to the code.

Go for the more understandable version, remember that "long" lines can be split into smaller chucks.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double distance = find_distance(car_center_x, car_center_y, goal_center_x, goal_center_y);
// Could also be:
double distance = find_distance(car_center_x, car_center_y, 
                                goal_center_x, goal_center_y);

Or maybe something more like:
...
struct Point
{
    int x;
    int y;
};
...
    Point car_center, goal_center;
...
    double distance = find_distance(car_center, goal_center);
...


Oh, and by the way main() must be defined to return an int in C++, int main()

Last edited on
I am a math purist, I guess, but I think X and Y are perfectly good variable names when talking about the X/Y plane in math, eg coordinates.
X and Y are not great names if just randomly stuff into code that does not refer to the X/Y plane, though. In general single letter variable names are mostly for loop counters and a VERY SELECT FEW places like the X/Y or X/Y/Z spaces, RGB color, or similar concepts where a single letter is actually descriptive as a name due to extreme common use of those letters. At that point its actually annoying and bloated to make big variable names. lets consider the same thing twice a couple of times to see this:
1) y = f(x); //granted f probably needs a better name, but y and x are fine.
2) theycoordinate = f(thexcoordinate);//bloat

and to really see the bloat effect:
1) 3*x*x - 2*x +11
2) 3*square(bloatedvariablename*bloatedvariablename)-2*(bloatedvariblename) + 11;

etc... it just gets worse and worse as you get into truly advanced equations.

size_t is an evil entity** that you really should use. The size of it varies across compilers and systems, and coding an integer or unsigned integer to accept its value can bite you. I just ran into this -- I do a lot of 1/2 page 'quick/disposable' programs, really simple stuff that I need to do in bulk over a file or something, and I moved one from my laptop to our server and it started having seg faults and garbled output and more. All that was wrong was an int that matched size-t on my laptop but was not the right byte-size on the server. Beware :)

** The number names for integer types is staggering, given that there are only about 10 real ones (1,2,4,8 bytes, unsigned of those is 8, and 2 more if you want to distinguish char and 1-byte ints for readability reasons). There are, I kid you not, at least 50 names for these and if you count microsoftisms that doubles again. Size_t is one of them. Word, long, long long, int8_t (one for each bit-count doubled for unsigned), … sigh.

Comments, again, your employer will tell you what they want, and your peers when you are trained. For now, comment what might confuse the reader and put something up top saying what it does.
1) 3*x*x - 2*x +11
2) 3*square(bloatedvariablename)-2*(bloatedvariblename) + 11;

FTFY
But yes you're 100% correct. A name should only be longer if it adds value. Changing "x" to "x_coordinate" doesn't add any useful information. But most variable names aren't just pure math equations.

multiple purposes (like logic and draw)
Drawing is one purpose. In my program, for example, I have an "OnPaint" function that does all the draw calls to the main screen, which is called every time there's a refresh event.

Your code example looks OK. Also don't be afraid to use spaces between lines to separate out different parts.

1
2
3
4
5
6
7
8
9
10
11
12
13
main()
{
  init();
  while (!quit)
  {
    read_controls();
    rotate_car();
    move_car();
    if (is_car_at_goal())
      quit = true;
    draw_car();
    draw_goal();
  }

This certainly isn't bad. It's still a short, straightforward function. What would be bad is not having those functions at all, and just jamming everything in main. I personally would space it out a bit, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
  init();
  while (!quit)
  {
    read_controls();

    rotate_car();
    move_car();
    if (is_car_at_goal())
      quit = true;

    draw_car();
    draw_goal();
  }

But it looks OK (as a kind of pseudo-code, obviously real code would have a bit more to keep track of).
Last edited on
closed account (Ezyq4iN6)
@jlb
That's good advice about using multiple lines. I have read somewhere that 80 characters is the most that you should have in a line. Is that accurate?

Also, I left off the int part from main() because I was trying to do more of pseudo code than anything else. I just forgot and put the return 0 there by mistake.

@jonin
So using a struct for points and the line where x, y are the only variables would be fine, right? What about other shortenings, like a for angle, etc?

Your point on bloat highlights what my fear is with large names, even if descriptive. When I get a long function or equation, I can only imagine how hard to read it may be. I have run into a few, but I generally try to slice out parts of the equation and create new variables, mainly to make it more readable for myself. I can imagine though, that this would be hard to read for others because now there are a bunch of pieces instead of one equation. It's a tough call to me.

If size_t is evil, especially because of the cross-platform issue, might things like int suffer from that same problem as well? Maybe not in the transfer between size_t -> int way, but you have an int you want to hold 16 bits, but then it only holds 8 on another system? Would using uint16_t and similar types be a better option? I'm considering switching to those, especially for all of my ints.

As I mentioned earlier, my professors are known for making us comment every line (which I guess isn't terrible for academic purposes and since the programs are so short (under 1000 lines usually)). However, on my own I usually only put a title and description at the top and a brief description at most for my function prototypes. Is this what you meant?
I have read somewhere that 80 characters is the most that you should have in a line. Is that accurate?
Some purists like to keep it to 80, but you don't need to. I generally don't go above 100. Some people like shorter widths so they can fit multiple columns of code on the screen. It's just personal taste (i.e. it's a "holy war" that has no right answer).

Don't worry about the specifics of size_t, I should have never brought it up. You don't need to worry about bit-fiddling like jonnin talks about. If you're writing binary files, yes prefer fixed sizes like "uint16_t" or "int8_t, etc.

No, in real life you should not be commenting every line. That's just a dumb academic thing to prevent students from just copying code they don't understand.
Yes, a brief description for your functions at the beginning sounds fine. If there's a particular part of the function that you think might be hard to follow, comment what that part does as well.

Last edited on
closed account (Ezyq4iN6)
@Ganado
Glad to know that the 80 character limit isn't set in stone.

I'll make a note about using those fixed sizes for binary files. I have done a little work with those, so it's a good thing to know.

I'm glad to know that excessive commenting is not needed in the "real world" of programming. I can't even imagine how cluttered it would make large programs look.

Thanks for all of your help.
If size_t is evil,

It's not evil, using the wrong type is the problem. A size_t is an implementation defined unsigned type and trying to use any "fixed size" type when dealing with something that is either returning or expecting a size_t is the problem.

but you have an int you want to hold 16 bits, but then it only holds 8 on another system? Would using uint16_t and similar types be a better option? I'm considering switching to those, especially for all of my ints.

Not necessarily.

Remember that most of those "fixed size" types are optional, so just willy-nilly switching to the "fixed size" types is not always the answer, and in many cases could cause performance issues, especially if you are trying to use the larger types like int64_t for all of your integers. A plain old int is usually considered the best option for most applications since it is usually considered the "natural" size for the system in question.
Hi,

With short variable identifiers for math related things, I think that is fine. For example:

std::size_t factorial(int n);

n is is fine , that is what you find in documentation everywhere.

Try to keep names the same as the documentation
80 chars is from dos days. There is no reason to adhere to that in a widescreen world where we have fonts and such.

you have to use size_t. I just think it was a poor choice to add it to the language. The .size() functions should return an unsigned long long, or something we already had. Its just yet another pointless int type.


use short names at your discretion. It should be obvious if its more readable or not. You want to use structs /classes a lot, but they sometimes are weird in pure math code. Honestly, very little code is pure math code, unless you are in a specialized field.






The .size() functions should return an unsigned long long, or something we already had. Its just yet another pointless int type.

long long was not added until C99/C++11. size_t goes back much longer.

size_t is a typedef so it could very well be the same type as unsigned long long.

Container::size() actually returns Container::size_type, which doesn't have to be the same as std::size_t (it normally is), but most people use std::size_t because it's easier to type and it's guaranteed to be large enough.
Last edited on
Pages: 12