473,585 Members | 2,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Good C programming style

Hi!

I'm thinking about a good programming style, pros and cons of some
topics. Of course, this has nothing to do with indentation... Students
are now java-dependent (too bad) and I need some serious motivations
for many issues... I hope you can help me :) I begin with the two major
for now, others will come for sure!

- function variables: they're used to java, so no pointers. Personally
I'd use always pointers, but why could be better to use:
void myfun(int &i) or (int *i) or (int i)
given that the function can and cannot (the last case of course) modify
a parameter. I see performance issues (stack related)...

- defines: why they use function and variable defines? why they shouldn't?
#define MY_PI 3.1415
#define fun(x) ((x) * (x))
--
Sensei <se******@mac.c om>

The difference between stupidity and genius is that genius has its
limits. (A. Einstein)

Nov 15 '05 #1
43 2623
"Sensei" <se******@tin.i t> wrote in message
news:di******** **@news.doit.wi sc.edu...
Hi!

I'm thinking about a good programming style, pros and cons of some topics.
Of course, this has nothing to do with indentation... Students are now
java-dependent (too bad) and I need some serious motivations for many
issues...
So you're teaching C?
I hope you can help me :) I begin with the two major for now, others will
come for sure!

- function variables: they're used to java, so no pointers. Personally I'd
use always pointers, but why could be better to use:
void myfun(int &i)
but you don't appear able to distinguish C from C++
or (int *i) or (int i)
given that the function can and cannot (the last case of course) modify a
parameter. I see performance issues (stack related)...
and you don't appear to be aware of the consensus about
premature optimization

- defines: why they use function and variable defines? why they shouldn't?
#define MY_PI 3.1415
#define fun(x) ((x) * (x))
and you don't appear to be aware of the type-checking that a
real function can give, and that macros do not.

Running quickly in the other direction,
-Mike
Nov 15 '05 #2
Sensei wrote:
I'm thinking about a good programming style, pros and cons of some
topics. Of course, this has nothing to do with indentation... Students
are now java-dependent (too bad) and I need some serious motivations for
many issues... I hope you can help me :) I begin with the two major for
now, others will come for sure!
The questions you're asking are elemental. Read a good book on C and
these topics should be treated in some detail, along with explanations
that will help you decide on what is appropriate and why.
- function variables: they're used to java, so no pointers. Personally
I'd use always pointers, but why could be better to use:
void myfun(int &i) or (int *i) or (int i)
int &i is not C. You may be thinking of C++.

As for when to use pointers and when not, it's simple: pointers for
variable-sized data like strings, pointers also to implement
call-by-reference in C, that is, arguments you'll need to change.
Pointers also for structs, see below. And finally, pointers for
functions, since there's no other way to pass them.
given that the function can and cannot (the last case of course) modify
a parameter. I see performance issues (stack related)...
Mostly irrelevant. A C idiom is to always pass structure types by
pointer because passing most structures by value means copying, which is
indeed a waste of time in most cases, especially if the value isn't
modified. While a compiler could optimize this in some cases, it's not
expected to, and programmers don't count on it.
- defines: why they use function and variable defines? why they shouldn't?
#define MY_PI 3.1415
Established C practice is to use #define for constants since C is a bit
puzzling when it comes to constants. Declaring a variable "const" does
not make its value a constant expression for purposes of array sizes,
for example. Also, memory is allocated for const variables (great
oxymoron, incidentally :-) when it typically isn't necessary.

There's no such thing as a "function" or "variable" define, however.
Macros just establish textual replacement rules.
#define fun(x) ((x) * (x))

Use functions when you can, macros when you have to. The example above
is a case of when you don't have to.

As for when you need macros, that's not a matter of coding style.

S.
Nov 15 '05 #3
Sensei <se******@tin.i t> writes:
I'm thinking about a good programming style, pros and cons of some
topics. Of course, this has nothing to do with indentation... Students
are now java-dependent (too bad) and I need some serious motivations
for many issues... I hope you can help me :) I begin with the two
major for now, others will come for sure!

- function variables: they're used to java, so no pointers. Personally
I'd use always pointers, but why could be better to use:
void myfun(int &i) or (int *i) or (int i)
given that the function can and cannot (the last case of course)
modify a parameter. I see performance issues (stack related)...
The term "function variables" is misleading; you mean parameters (the
things declared between the parentheses in a function declaration) or
arguments (the actual values passed in a function call).

The declaration "void myfun(int &i)" is not valid C. (I think it's
C++; see comp.lang.c++.)

The choice between "void myfun(int *p)" and "void myfun(int i)" isn't
really a matter of style; it's just a matter of what the function
needs to do. (Note that I've changed the name of the pointer
parameter; calling a pointer "i" is misleading.) If myfun needs to
change the value of an object specified by the caller, or if you want
to point to an array of integers, use a pointer. If you just want to
pass an integer value, use an int.

Note that if myfun's parameter is a pointer, you can only pass the
address of an ojbect (or a null pointer); you can't pass 42 or x+3.

If the parameter is of a struct type, it often makes sense to pass a
pointer even if you don't want to modify the struct object. Passing
an argument means making a copy of the argument and storing it in the
parameter; for large structures, this can be significantly expensive.
This consideration doesn't apply to ints, since there's no significant
performance difference between passing a copy of an int and passing a
copy of its address.
- defines: why they use function and variable defines? why they shouldn't?
#define MY_PI 3.1415
#define fun(x) ((x) * (x))


For MY_PI (BTW, everybody else's PI is closer to 3.1416), C doesn't
provide a mechanism for defining a constant floating-point value. You
can declare
const double my_pi = 3.1415926535897 9323848264;
but that creates a write-only variable, not a real constant. Macros
are useful for this kind of thing.

As for function-like macros, they're sometimes the best way to create
inline functions. (C99 has inline functions, but not all compilers
support them.) There are also things you can do in a macro that you
can't easily do in a function, such as using a type name as an
argument. But try not to be too tricky. Macros can be dangerous,
since they're expanded in a very early stage of compilation. They can
*look* like function calls or variable declarations, but they don't
necessarily act like them; for example, they pay no attention to
scope.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #4
Keith Thompson wrote:
<snip>
You can declare
const double my_pi = 3.1415926535897 9323848264;
but that creates a write-only variable, not a real constant. Macros
are useful for this kind of thing.

You know, a write-only variable is about the only thing C's missing. :-D

S.
Nov 15 '05 #5
Sensei wrote:
Hi!

I'm thinking about a good programming style, pros and cons of some
topics. Of course, this has nothing to do with indentation... Students
are now java-dependent (too bad) and I need some serious motivations for
many issues... I hope you can help me :) I begin with the two major for
now, others will come for sure!

- function variables: they're used to java, so no pointers. Personally
I'd use always pointers, but why could be better to use:
void myfun(int &i) or (int *i) or (int i)
void myfun(int &i) is an error in C. The two options that are C that you
list are
void myfun(int *i)
void myfun(int i)
given that the function can and cannot (the last case of course) modify
a parameter. I see performance issues (stack related)...
C does not require a stack, but assuming a stack implementation in
either case something will be pushed on to it, either the value of an
int or a pointer to an int. Do you *really* think either will have a
significant performance difference?

Write what you mean, don't try to micro-optimise.
- defines: why they use function and variable defines? why they shouldn't?
#define MY_PI 3.1415
How else would you define MY_PI? Apart from more accurately, that is ;-)
#define fun(x) ((x) * (x))


In this instance fun will work on any arithmetic type which can
sometimes be an advantage. I would generally recommend using functions
rather than function like macros *except* where you have a specific
reason to need a function like macro (e.g. if you wanted fun above to
operate on any arithmetic type and not have it convert everything to
double or long double).

Macro's can have unexpected effects such as given the above definition
if you do
fun(a++)
you actually invoke undefined behaviour because it will expand to
((a++) * (a++))
which attempts to modify a twice without an intervening sequence point.
This is why you should not use function like macros except where you
need them. It is also why you should follow the convention of spelling
macros in UPPER CASE to give people an immediate warning.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #6
Skarmander wrote:
Keith Thompson wrote:
<snip>
You can declare
const double my_pi = 3.1415926535897 9323848264;
but that creates a write-only variable, not a real constant. Macros
are useful for this kind of thing.

You know, a write-only variable is about the only thing C's missing. :-D

S.


The write-only characteristic is priceless. In a former life I designed
a ram-disk subsystem, memory which should 'look' like a disk drive.
Until I got it working, I referred to it as write-only memory.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 15 '05 #7

Sensei wrote:
Hi!

I'm thinking about a good programming style, pros and cons of some
topics. Of course, this has nothing to do with indentation... Students
are now java-dependent (too bad) and I need some serious motivations
for many issues... I hope you can help me :) I begin with the two major
for now, others will come for sure!

- function variables: they're used to java, so no pointers. Personally
I'd use always pointers, but why could be better to use:
void myfun(int &i) or (int *i) or (int i)
int &i is not standard C.
given that the function can and cannot (the last case of course) modify
a parameter. I see performance issues (stack related)...

- defines: why they use function and variable defines? why they shouldn't?
#define MY_PI 3.1415
You might want to extend pi a few more decimal places. The SUSv3
standard has a macro M_PI in <math.h>, but it isn't ISO-99 C.
#define fun(x) ((x) * (x))
This is considered bad style for a macro because the macro argument is
evaluated twice. Imagine what would happen if the argument to the macro
contained an increment or decrement operator.

Gregory Pietsch


--
Sensei <se******@mac.c om>

The difference between stupidity and genius is that genius has its
limits. (A. Einstein)


Nov 15 '05 #8
Joe Wright wrote:
Skarmander wrote:
Keith Thompson wrote:
<snip>
You can declare
const double my_pi = 3.1415926535897 9323848264;
but that creates a write-only variable, not a real constant. Macros
are useful for this kind of thing.

You know, a write-only variable is about the only thing C's missing. :-D


The write-only characteristic is priceless. In a former life I designed
a ram-disk subsystem, memory which should 'look' like a disk drive.
Until I got it working, I referred to it as write-only memory.

I have actually worked on machines that had write-only memory, typically
memory-mapped hardware (the addresses corresponding to "out" ports of
some sort, of course). Aside from the curiousity value, it's really not
that different from regular memory -- you won't use it to store
temporaries or read back what you've written, after all.

S.
Nov 15 '05 #9
Keith Thompson wrote:
const double my_pi = 3.1415926535897 9323848264;


Where the hell did you get the idea that the next digit after
3.1415926535897 932384 was 8?!!!

;)

--
pete
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
3571
by: matty | last post by:
Go away for a few days and you miss it all... A few opinions... Programming is a craft more than an art (software engineering, not black magic) and as such, is about writing code that works, first and foremost. If it works well, even better. The same goes for ease of maintenance, memory footprint, speed, etc, etc. Most of the time,...
29
1988
by: Cheng Mo | last post by:
Recently I happens to read some sourcecode which has different style from my previous experience. In this style, all functions return a RETURN_TYPE_T which is defined as typedef unsigned int RETURN_TYPE_T; and the return value can only be enum value enum { SUCCESS = 0, FAILURE = 1,
20
5118
by: Clark | last post by:
Hi all. I'm looking for good C source code to study and be able to advance my C programming skills. Do you recomend any open source project in particular that in your opinion has good writen C code? Thanks.
60
3924
by: K. G. Suarez | last post by:
Hello everyone. I am new to programming and my uncle gave me a copy of "C For Dummies 2nd Edition". I am up to chapter 9 right now. He probably saw me struggling with "The C Programming Language" by Ritchie and Kernigahn and felt bad. Does anyone have experience with this book? I feel that it is helping me along pretty well. But how much...
2
315
by: Harley | last post by:
Hello, I was VERY blessed with a Christmas gift of visual studio .net from a man I hardly know who had heard of my plans of software developement. So I am probably the only person in the world who actualy has this great IDE and don't even know vb.net (or c sharp etc.). I have some prior exposure to simple scripting language such as...
0
1207
by: André | last post by:
I'm trying to change an app so that it uses gettext for translations rather than the idiosyncratic way I am using. I've tried the example on the wxPython wiki http://wiki.wxpython.org/index.cgi/RecipesI18n but found that the accented letters would not display properly. I have found a workaround that works from Python in a Nutshell; however...
206
8257
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a footprint which says: "Indeed, one often hears arguments against building exibility into an engineered sys- tem. For example, in the philosophy of...
2
1965
by: silvrfoxx | last post by:
I created this using notepad and was checking it in Firefox, but when i finished and checked it in IE it looks like crap. I even opened up Dreamweaver and it shows it looking great. I can't find what is causing it. I have double, triple checked to make sure that all my ", <, >, tr, td, etc. are opened and closed properly. Please can anyone...
14
1828
by: Astley Le Jasper | last post by:
I'm still learning python and would like to know what's a good way of organizing code. I am writing some scripts to scrape a number of different website that hold similar information and then collating it all together. Obviously each site needs to be handled differently, but once the information is collected then more generic functions can...
0
7904
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7835
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8195
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
6596
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5386
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3856
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2340
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1444
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1171
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.