Coding Pet Peeve of Mine

I’ve noticed that Ben likes to place his variables within his functions right before they are used. I find that this style tends to confuse me a bit, so I’ve been sticking to my own formatting for variables.

For example, Ben’s variable formatting style:

void main()
{
string red = "red";
cout << red;

string blue = "blue";
cout << blue;

string yellow = "yellow";
cout << yellow;
}

My formatting style:

void main()
{
string red = "red";
string blue = "blue";
string yellow = "yellow";

cout << red;
cout << blue;
cout << yellow;
}

Basically, I just like to keep all the variables at the top of their scope in a list format. Both formats are perfectly fine, but some people may find mine helps them stay more organized. It’s all comes down to preference really. Hope this helps :smiley:

1 Like

Hi Donald, thanks for speaking-up on this.

With these short code examples there’s little difference between either style, and I agree yours is “prettier”

However, what I’m trying to ingrain here is the habit of keeping the variables “live” for as short a time as possible.

This is covered in some detail from page 245 of Steve McConnel’s excellent book called Code Complete.

This really helps to keep track in larger methods, that could be dozens of lines long. It means we don’t have to remember much as we read through.

Thanks again and enjoy the course(s)

1 Like

Makes sense. I’ll try using your style for a while and see if I can get my brain to comply. I’ve always been taught to use my current style, but in my previous courses our functions never got to be very large.

1 Like

Privacy & Terms