Author Topic: Suggestion on naming variables C  (Read 12715 times)

0 Members and 1 Guest are viewing this topic.

Offline Vindhyachal.takniki

  • Frequent Contributor
  • **
  • Posts: 375
Suggestion on naming variables C
« on: March 24, 2015, 05:28:00 am »
Now I am trying to name variables by below method. Any suggestions/comments

1. All vars should of be atleast 3 chars like cnt,loop. Declaring i is incorrect.
2. Datatype of var should be visible from its name Like u32_cnt.


1.Global var: g_u32_loop
2. global constant: gc_u8_loop
3. Static var: s_i16_loop;
4. static constant: sc_c8_loop;
5. local var: f32_loop;
6. local const: c_f64_loop;
7. ptr: p_u16_cnt
 

Offline cellularmitosis

  • Supporter
  • ****
  • Posts: 1047
  • Country: us
Re: Suggestion on naming variables C
« Reply #1 on: March 24, 2015, 06:45:24 am »
You'll find these style choices are largely dependent upon how powerful your editor.

In Xcode, for example, I no longer shy away from verbose names.  When you have intelligent autocomplete and refactoring tools, class names like MyShipmentsViewController become commonplace (rather than something like ShipmntsVC).

But you are already on the most important part of the path: become opinionated and desire to follow conventions of your own design, because you care about the little things!  Over the next five years you will change your personal conventions a dozen times, and that's ok.
LTZs: KX FX MX CX PX Frank A9 QX
 

Offline krish2487

  • Frequent Contributor
  • **
  • Posts: 437
  • Country: dk
Re: Suggestion on naming variables C
« Reply #2 on: March 24, 2015, 06:57:05 am »
as cellularmitosis has suggested - these issues are largely individual in nature.
However,
read about hungarian naming convention and MISRA C rules.
In the end, develop a system that works for you and that you can maintain and implement consistently. Developing a system is easy, consistently using it is hard. So develop a system that is easy to follow.
If god made us in his image,
and we are this stupid
then....
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5549
  • Country: us
Re: Suggestion on naming variables C
« Reply #3 on: March 24, 2015, 07:05:09 am »
as krish2487 suggests read up on hungarian notation
http://en.wikipedia.org/wiki/Hungarian_notation

at least that way if someone needs to collaborate in the source, they will be familiar with that notation.
« Last Edit: March 24, 2015, 07:07:06 am by miguelvp »
 

Online sleemanj

  • Super Contributor
  • ***
  • Posts: 2455
  • Country: nz
  • Professional tightwad.
    • The electronics hobby components I sell.
Re: Suggestion on naming variables C
« Reply #4 on: March 24, 2015, 07:19:52 am »

2. Datatype of var should be visible from its name Like u32_cnt.


I hate that personally, not only because it's pointless nomenclature which can readily be seen by looking at the variable definition (and if you can't remember the variable definition, how are you going to remember the variable name anyway!), but because if you ever want to change the type (or potentially even machine architecture) now instead of changing a handful of definitions, you have to go through and change all the variable names, AND remember these new variable names, many of which are virtually in muscle memory if you are writing the code for any length of time.

Similarly, mandating that variables be "3 characters" is silly, there are countless times when you require simple indexes in a for loop - x, i, j and k are well-trodden and perfectly good index variable names, as long as their scope is small.

As far as I'm concerned such floweriness is just superfluous cruft designed to waste keystrokes and slow the thought process when mentally referring to variables.

It's bad enough using stupid datatype names like "uint_8" instead of the perfectly simple "byte".


 

~~~
EEVBlog Members - get yourself 10% discount off all my electronic components for sale just use the Buy Direct links and use Coupon Code "eevblog" during checkout.  Shipping from New Zealand, international orders welcome :-)
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5549
  • Country: us
Re: Suggestion on naming variables C
« Reply #5 on: March 24, 2015, 07:35:49 am »
I personally don´t like them (hungarian notation or the like) but sometimes I must use them if the piece of code at hand follows that standard.
I kind of tend to try not to leave mismatch notation/format trails.

Plus nowadays IDEs will let you know what it is just by hovering over it.
 

Offline Stupid Beard

  • Regular Contributor
  • *
  • Posts: 221
  • Country: gb
Re: Suggestion on naming variables C
« Reply #6 on: March 24, 2015, 07:38:32 am »
Read http://www.joelonsoftware.com/articles/Wrong.html
Read it all.
Kill the abomination now before it is too late.
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 3397
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: Suggestion on naming variables C
« Reply #7 on: March 24, 2015, 08:24:22 am »
"uint8_t" types are defined in stdint.h, "byte" isn't.
Using byte will give you an extra useless define creating a type that is unnecessary.

Instead of prefixing the type. Prefix the module if you extern them.
Prefixing the type might help if you have a lot of casts and your code needs to be validated.
 

Offline Michaela Joy

  • Contributor
  • Posts: 20
  • Country: us
Re: Suggestion on naming variables C
« Reply #8 on: March 29, 2015, 04:40:26 pm »
@Stupid_Beard: That article is -great-  :-+ Thanks for posting it.

If you're coding a project yourself, then use whatever naming convention makes the most sense to you. If someone else may need to or will be working on your code, then make it as readable and understandable as possible. Use comments on things that are not clear, but do not over-comment.

:MJ
For a successful technology, reality must take precedence over public relations. For nature can not be fooled.
 

Offline elgonzo

  • Supporter
  • ****
  • Posts: 690
  • Country: 00
Re: Suggestion on naming variables C
« Reply #9 on: March 29, 2015, 04:50:40 pm »
It's bad enough using stupid datatype names like "uint_8" instead of the perfectly simple "byte".
While i agree with the rest of your argument, i disagree with this particular sentence.
"uint_8" makes it explicitly clear what range of values can be represented by this datatype: [0,255].
"byte" is less clear about this - is it a signed or unsigned data type? Unfortunately the datatype "byte" is already used differently by different programming languages/frameworks - for example, in Java byte is signed ([-128,127]), in C# it is unsigned ([0,255]). Speaking about "perfectly simple", ehh... ;)


@Stupid_Beard, +1 for linking this execellent article :)
« Last Edit: March 29, 2015, 05:08:36 pm by elgonzo »
 

Offline IanB

  • Super Contributor
  • ***
  • Posts: 9618
  • Country: us
Re: Suggestion on naming variables C
« Reply #10 on: March 29, 2015, 04:57:59 pm »
Now I am trying to name variables by below method. Any suggestions/comments

1. All vars should of be atleast 3 chars like cnt,loop. Declaring i is incorrect.
2. Datatype of var should be visible from its name Like u32_cnt.


1.Global var: g_u32_loop
2. global constant: gc_u8_loop
3. Static var: s_i16_loop;
4. static constant: sc_c8_loop;
5. local var: f32_loop;
6. local const: c_f64_loop;
7. ptr: p_u16_cnt

There's nothing wrong with using single letters like i, j, k as loop variables (as long as it is a small loop and the scope of the variable is clear). Mind you, making big long loops that don't fit on the screen is bad design, so don't do that.

Try to make all variable names read like proper language (human language or mathematical language). Use words that describe the contents of the variable, like "itemPrice" or "itemQuantity". Do not waste letters on things like "u16" or "f32" since the variable declaration holds that information and a good code editor can quickly tell you what it is.

In mathematical language it is common to index an array as, for instance, aij , so it's quite natural to write a[i,j] in code to mean the same thing.
I'm not an EE--what am I doing here?
 

Offline economist

  • Contributor
  • Posts: 41
  • Country: us
Re: Suggestion on naming variables C
« Reply #11 on: March 29, 2015, 05:39:11 pm »
There's nothing wrong with using single letters like i, j, k as loop variables (as long as it is a small loop and the scope of the variable is clear). Mind you, making big long loops that don't fit on the screen is bad design, so don't do that.

Try to make all variable names read like proper language (human language or mathematical language). Use words that describe the contents of the variable, like "itemPrice" or "itemQuantity". Do not waste letters on things like "u16" or "f32" since the variable declaration holds that information and a good code editor can quickly tell you what it is.

In mathematical language it is common to index an array as, for instance, aij , so it's quite natural to write a[i,j] in code to mean the same thing.

Completely agree with this. In 30 years of coding in various languages I always come back to readability of code as being the key thing. Follow that with consistency and plenty of comments and just about any sensible system can work.
 

Offline bitshift

  • Regular Contributor
  • *
  • Posts: 155
  • Country: za
  • Too much to learn, too little time
Re: Suggestion on naming variables C
« Reply #12 on: March 29, 2015, 06:15:55 pm »
Now I am trying to name variables by below method. Any suggestions/comments

1. All vars should of be atleast 3 chars like cnt,loop. Declaring i is incorrect.
2. Datatype of var should be visible from its name Like u32_cnt.


1.Global var: g_u32_loop
2. global constant: gc_u8_loop
3. Static var: s_i16_loop;
4. static constant: sc_c8_loop;
5. local var: f32_loop;
6. local const: c_f64_loop;
7. ptr: p_u16_cnt

There's nothing wrong with using single letters like i, j, k as loop variables (as long as it is a small loop and the scope of the variable is clear). Mind you, making big long loops that don't fit on the screen is bad design, so don't do that.

Try to make all variable names read like proper language (human language or mathematical language). Use words that describe the contents of the variable, like "itemPrice" or "itemQuantity". Do not waste letters on things like "u16" or "f32" since the variable declaration holds that information and a good code editor can quickly tell you what it is.

In mathematical language it is common to index an array as, for instance, aij , so it's quite natural to write a[i,j] in code to mean the same thing.

+1

Just to add, I don't think you should separate identifiers with the "_" character. While this could be considered "nice to read", its a bitch to type because you have to hold shift.

Some of the major "rules" I tend to follow:
  • Always think about how the next guy reading your code will interpret it. He won't necessarily have the same context you have so keep it simple and readable.
  • "Never" use abbreviations. Rather use full names like itemQuantity over itemQty. This example is obvious, but it won't always be.
  • Avoid generic names like "loop". Your variable names should describe their semantic function.
  • Favor readability and maintainability over performance. Only worry about performance once you've identified a problem.
  • In whatever you choose be consistent.

This rather short list could go on forever...

In summary, keep it simple, short and readable!
"It’s all fun and games until an innocent opamp gets hurt!" - Dave Jones
 

Offline Howardlong

  • Super Contributor
  • ***
  • Posts: 4814
  • Country: gb
Re: Suggestion on naming variables C
« Reply #13 on: March 29, 2015, 07:03:37 pm »
Having your own standard is a personal thing, and being religious about it saying something like camel case is stupid, or Hungarian notation is for losers is like me saying you're stupid if you like peanut butter and jelly sandwiches. It's a personal taste, I don't get peanut butter and jelly sandwiches, but I'm not going to deprive or denigrate someone if they like them.

In support of Hungarian notation, the point is, particularly in C, to make an effort to save programmers from themselves when they do silly things like signed/unsigned comparisons or other implicit type conversions. These days, as long as the warning level is sufficiently high, the compiler will complain, and yes, we do have editors these days that will tell you the type. However despite this I have see enough missed (or worse, deliberately hacked) silly type conversion functional bugs in my life, from programmers who I thought would know better, to realise that having some indication of type in the variable name is not superfluous to my mind. Finally, I've been doing HN since the late 80s and I'm a bit long in the tooth to start changing now, I'm comfortable in my own skin if you like.

However, I am open minded enough to accept that other folks see Hungarian notation as unnecessary, and I don't get all precious about it if that's what floats (did you see what I did there?) their boat.

What is more important than coding standards (whatever they may be) is maintaining consistency.
 

Online mikerj

  • Super Contributor
  • ***
  • Posts: 2288
  • Country: gb
Re: Suggestion on naming variables C
« Reply #14 on: March 29, 2015, 07:11:40 pm »
It's bad enough using stupid datatype names like "uint_8" instead of the perfectly simple "byte".

Particularly in embedded systems, the fixed width datatypes are extremely useful.  A 'byte' might be an octet on the majority of platforms, but that doesn't help you when you are working on one of the exceptions.  What name would you give to e.g. 16 bit and 32bit data types that clearly relates to the data types size and would remains consistent on all platforms?
 

Offline Howardlong

  • Super Contributor
  • ***
  • Posts: 4814
  • Country: gb
Re: Suggestion on naming variables C
« Reply #15 on: March 30, 2015, 12:31:43 am »
It's bad enough using stupid datatype names like "uint_8" instead of the perfectly simple "byte".

Particularly in embedded systems, the fixed width datatypes are extremely useful.  A 'byte' might be an octet on the majority of platforms, but that doesn't help you when you are working on one of the exceptions.  What name would you give to e.g. 16 bit and 32bit data types that clearly relates to the data types size and would remains consistent on all platforms?

 :-+

Before stdint.h became generally established, I had implementation specific typedefs in a header file, eg S8, S16, S32 and U8, U16 etc. It allowed me to easily test algorithms natively on the PC that eventually might target 8 or 16 bit embedded systems. Using BYTE is not so bad, but far worse is WORD as in Windows which was was a silly mistake for the Windows guys, especially when they started messing with WPARAM. Pretty much every port from Win16 to Win32 was became time consuming chore as a result.
 

Online xrunner

  • Super Contributor
  • ***
  • Posts: 4515
  • Country: us
  • hp>Agilent>Keysight>?
Re: Suggestion on naming variables C
« Reply #16 on: March 30, 2015, 12:40:09 am »
In college I had a schoolmate that wrote a program and all his variable names were ... ahem ... basically profanity. Then, when he couldn't get it to work per the assignment, he had to take it to the professor at the last minute and didn't have time to change all the variable names. I wish I had been a fly on the wall in that room.  ;)
I am a Test Equipment Addict (TEA) - by virtue of this forum signature, I have now faced my addiction
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2018
  • Country: au
Re: Suggestion on naming variables C
« Reply #17 on: March 30, 2015, 12:43:05 am »
In college I had a schoolmate that wrote a program and all his variable names were ... ahem ... basically profanity.

Although I use it all the time, I often find cnt troubling :)
 

Offline alexanderbrevig

  • Frequent Contributor
  • **
  • Posts: 589
  • Country: no
  • Musician, programmer and EE hobbyist
    • alexanderbrevig.com
Re: Suggestion on naming variables C
« Reply #18 on: March 30, 2015, 12:51:43 am »
When I review code, there are a few rules that - when broken - will prompt me to give up on the project or the programmer:

  • No hungarian notation (g_pasz_dictionary  |O)
  • No flooding of global variables, there should be as few as possible
  • Undescriptive or overly technical variable names
  • Too much or too little commenting (the code should document itself as much as possible)

Things like casing, spacing, tabs, order of declaration etc are things of less importance.
If I must contribute to a team with extremely weird formatting, then I convince them to specify their rules as an AStyle format, then I have hooks with git that translates to- and from their format upon commits.

tl;dr

Please do not ever use hungarian notation. Not. Ever.  :-+

And this joke:
Code: [Select]
/* it was hard to write, and should be hard to read */Is only funny when you do not read it as the only comment in a file.
« Last Edit: March 30, 2015, 12:54:14 am by alexanderbrevig »
 

Offline Howardlong

  • Super Contributor
  • ***
  • Posts: 4814
  • Country: gb
Re: Suggestion on naming variables C
« Reply #19 on: March 30, 2015, 01:07:29 am »
When I review code, there are a few rules that - when broken - will prompt me to give up on the project or the programmer:
...
Please do not ever use hungarian notation. Not. Ever.  :-+

Crikey, sounds like you're running a fun ship there, must be a barrel of laughs!

While it is valid to adopt the house coding style to create consistency, and that outweighs the choice of coding standards themselves, there are other opinions out there ya know. I didn't actually see your justification in opposing HN, I might've missed it though.
 

Offline Mechatrommer

  • Super Contributor
  • ***
  • Posts: 9386
  • Country: my
  • reassessing directives...
Re: Suggestion on naming variables C
« Reply #20 on: March 30, 2015, 01:58:12 am »
Now I am trying to name variables by below method. Any suggestions/comments
1.Global var: g_u32_loop
2. global constant: gc_u8_loop
3. Static var: s_i16_loop;
4. static constant: sc_c8_loop;
5. local var: f32_loop;
6. local const: c_f64_loop;
7. ptr: p_u16_cnt
good luck typing all that in your code. my rule is... readable while easy to type... above all dont give personal taste too much emotionally attached, it can waste alot of good time that can be spent coding real stuffs. there is one tool that can fix every problem in this universe... edit->replace. i was in your path....
« Last Edit: March 30, 2015, 02:01:40 am by Mechatrommer »
if something can select, how cant it be intelligent? if something is intelligent, how cant it exist?
 

Offline Stupid Beard

  • Regular Contributor
  • *
  • Posts: 221
  • Country: gb
Re: Suggestion on naming variables C
« Reply #21 on: March 30, 2015, 02:08:26 am »
When I review code, there are a few rules that - when broken - will prompt me to give up on the project or the programmer:
...
Please do not ever use hungarian notation. Not. Ever.  :-+

Crikey, sounds like you're running a fun ship there, must be a barrel of laughs!

While it is valid to adopt the house coding style to create consistency, and that outweighs the choice of coding standards themselves, there are other opinions out there ya know. I didn't actually see your justification in opposing HN, I might've missed it though.

It depends which version of hungarian. I don't know what the original poster was getting at, but this is what goes through my head when I see hungarian notation:

If it is used to indicate the type of the variable then that is an indication that that programmer doesn't understand the actual intent behind hungarian notation and has almost certainly just made things more annoying to read and write for no clear benefit.

If it is used to indicate the actual datatype (e.g. null terminated string vs string terminated in some other way) then as long as they haven't also used it in the misinterpretation way, that's generally sensible. I wouldn't say required, but I can understand why you'd do it.

If it is used to indicate something important, for example to separate unsafe data from safe or sanitized data, then that is a very sane thing to do that everybody should do to some degree, depending on what their code is for. It is hard to form an argument against that because using the wrong thing in the wrong place can have catastrophic consequences far beyond your code.

In my opinion it is important to understand the genuine reasoning behind things and separate out what is just personal preference. In the case of hungarian notation, if you do that and still prefer to use the misinterpretation of it then that's totally fine.

It should also be clear from the above that blindly saying "fuck hungarian notation" without understanding why it was used is just as incorrect as blindly using it.
« Last Edit: March 30, 2015, 02:37:23 am by Stupid Beard »
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2195
  • Country: nz
Re: Suggestion on naming variables C
« Reply #22 on: March 30, 2015, 02:58:45 am »
Please do not ever use hungarian notation. Not. Ever.  :-+

When I first came across Hungarian notation, it was in the days of Windows 3.0.

I feel it came about as in those days programmers got quickly confused by they way programming environment and resources greatly exceeded what could easily be addressed (remember the days of near, huge and far pointers?), and PC coders were just getting used to the idea that they didn't own everything.

The API was also a bit cluggy, with some interfaces requiring handles, others requiring pointers, some needing handles to pointers, then there were WORDs, DWORDs and QWORDs and so on. Also i10n/i18n was also big, so Unicode support became an issue, and new territory for most coders.

To make matters worse you sometimes had to cast from one type to another - e.g. you might have a handle to a device context, but cast it to a generic handle for an API call (e.g. to release the handle).

The standard response of the time was to be explicit about what everything was, so it sort of became instantly apparent if you had typing issues - hDC, hBrush, nCount, pszText, cConstant, cszNullTerminatedStringConstant, pcszPointerToNullTerminatedString blah, blar, blar.

Now that the problems which caused the issues have largely gone away. We have OOP languages, extensive class libraries encapsulating and hide the rougher edges of APIs, better languages and/or better compilers with better type better checking, oodles of RAM, CPUs with registers that can hold pointers pointers that can address the full memory space and so on.  And we also have awesome IDEs that will tell you want a variable is just by hovering a pointer over it.

Because of this Hungarian notation is largely a relic. However, also have a lot of programmers who found great utility in using it to address what are largely yesterday's problems, so some people have become very attached to it.

Strangely enough, UNIX is largely free of this, as everything was pretty much a 32 bit integer or a 32 bit pointers and the OS API was relatively clean - for example, sockets, pipes and file handles are just integers and you can read or write from either, not hFile, hPipe or hSocket .


Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline 691175002

  • Regular Contributor
  • *
  • Posts: 64
Re: Suggestion on naming variables C
« Reply #23 on: March 30, 2015, 03:53:03 am »
I used to use Hungarian notation in the past but over time I realized it was just a huge waste of time, and is very uncommon among other programmers.

Ninety nine percent of the time the type of a variable should be obvious from its context.  In the rare cases where it isn't, use a comment to clarify.

I've noticed that you generally only see underscores in code that is a least a decade old as well.  Nobody needs to type the _ character when camel case is just as good.  Only place I would use them are in all-caps constants.
 

Offline c4757p

  • Super Contributor
  • ***
  • Posts: 7805
  • Country: us
  • adieu
Re: Suggestion on naming variables C
« Reply #24 on: March 30, 2015, 04:00:34 am »
You dislike underscores of all things? I find snake_case to be significantly more legible than CamelCase.
No longer active here - try the IRC channel if you just can't be without me :)
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf