473,385 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Function and variable declarations

Hello all,

Here's a brief function from the aforementioned (and controversial) GNU
Scientific Library (GSL), or rather, a slightly rewritten version of it
that I've made. The function takes an integer and sets up certain
necessary values for a random number generator. x, n and shuffle in
this function are global variables.

/************************************************** ***********/
static void
ran1_set (unsigned long int s) {
int i;

if(s==0)
s = 1;

for(i=0;i<8;++i) {
long int h = s / q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
}

for(i=N_SHUFFLE-1;i>=0;--i) {
long int h = s/q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
shuffle[i] = s;
}

x = s;
n = s;

return;
}
/************************************************** ***********/

Anyway, two questions:

(1) why declare the function a "static void" instead of just void? (My
personal use of "static" is just to preserve values between different
calls to modules or functions, but I know its use can be more complex
than this.)

(2) Any particular reason why the long int's h and t are declared twice
inside different loops, instead of just being declared at the beginning
of the function?

Many thanks,

-- Joe

Nov 26 '05 #1
20 1355

"Joseph Wakeling" <jo*************@gmail.com> wrote in message
news:11*********************@o13g2000cwo.googlegro ups.com...
Hello all,

Here's a brief function from the aforementioned (and controversial) GNU
Scientific Library (GSL), or rather, a slightly rewritten version of it
that I've made. The function takes an integer and sets up certain
necessary values for a random number generator. x, n and shuffle in
this function are global variables.

/************************************************** ***********/
static void
ran1_set (unsigned long int s) {
int i;

if(s==0)
s = 1;

for(i=0;i<8;++i) {
long int h = s / q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
}

for(i=N_SHUFFLE-1;i>=0;--i) {
long int h = s/q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
shuffle[i] = s;
}

x = s;
n = s;

return;
}
/************************************************** ***********/

Anyway, two questions:

(1) why declare the function a "static void" instead of just void? (My
personal use of "static" is just to preserve values between different
calls to modules or functions, but I know its use can be more complex
than this.)

(2) Any particular reason why the long int's h and t are declared twice
inside different loops, instead of just being declared at the beginning
of the function?


1. The use of static for a function restricts the function's visibility - to
that of the translation unit (file) it's defined in.

2. As far as I know - Nope.
Nov 26 '05 #2
Joseph Wakeling wrote:
static void
ran1_set (unsigned long int s) { <snip> for(i=0;i<8;++i) {
long int h = s / q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
}

for(i=N_SHUFFLE-1;i>=0;--i) {
long int h = s/q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
shuffle[i] = s;
} <snip> (1) why declare the function a "static void" instead of just void? (My
personal use of "static" is just to preserve values between different
calls to modules or functions, but I know its use can be more complex
than this.)
"static" in declarations has two different meanings; one is to give an
identifier static storage (the use you describe), the other is to give
it internal linkage (this use). Here "static" just means "not extern",
that is, the function symbol is internal to the unit and inaccessible
from the outside. This improves modularity.

There's actually a third meaning in C99, used in passing array
parameters, but if you're interested in this you can look it up. You're
not likely to encounter it in the wild yet. And we'll ignore C++, which
assigns yet another meaning to it.
(2) Any particular reason why the long int's h and t are declared twice
inside different loops, instead of just being declared at the beginning
of the function?

Declaring variables in the innermost block they are used in is good for
readability and may have positive effects on register usage too. In this
case it doesn't buy you much, but it's not hurting anyone either.

S.
Nov 26 '05 #3
Joseph Wakeling wrote:
Hello all,

Here's a brief function from the aforementioned (and controversial) GNU
Scientific Library (GSL), or rather, a slightly rewritten version of it
that I've made. The function takes an integer and sets up certain
necessary values for a random number generator. x, n and shuffle in
this function are global variables.

/************************************************** ***********/
static void
ran1_set (unsigned long int s) {
int i;

if(s==0)
s = 1;

for(i=0;i<8;++i) {
long int h = s / q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
}

for(i=N_SHUFFLE-1;i>=0;--i) {
long int h = s/q;
long int t = a * (s - h * q) - h * r;
if(t < 0)
t += m;
s = t;
shuffle[i] = s;
}

x = s;
n = s;
Global (or at least file scope) variable named x and n? Yuk.
return;
Rather pointless having a return here IMHO.
}
/************************************************** ***********/

Anyway, two questions:

(1) why declare the function a "static void" instead of just void? (My
personal use of "static" is just to preserve values between different
calls to modules or functions, but I know its use can be more complex
than this.)
When used on a function or a variable at file scope it means
approximately "don't make the name available to other modules." Or, to
use standard terminology, it only has internal linkage.
(2) Any particular reason why the long int's h and t are declared twice
inside different loops, instead of just being declared at the beginning
of the function?


It's called minimising scope. Because they are declared in the loop you
know, without having to check, that they are not used outside.
Otherwise, you would have to read beyond the end of the loop to see if
the last value gets used outside the loop.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 26 '05 #4

"Skarmander" <in*****@dontmailme.com> wrote in message
news:43***********************@news.xs4all.nl...
<snip>

There's actually a third meaning in C99, used in passing array parameters,
but if you're interested in this you can look it up. You're not likely to
encounter it in the wild yet. And we'll ignore C++, which assigns yet
another meaning to it.


void f(double a[static 3]);

Specifies that the argument corresponding to 'a' in any call to f must be a
non-null pointer to the first element????
Nov 26 '05 #5
rayw wrote:
"Skarmander" <in*****@dontmailme.com> wrote in message
news:43***********************@news.xs4all.nl...
<snip>
There's actually a third meaning in C99, used in passing array parameters,
but if you're interested in this you can look it up. You're not likely to
encounter it in the wild yet. And we'll ignore C++, which assigns yet
another meaning to it.


void f(double a[static 3]);

Specifies that the argument corresponding to 'a' in any call to f must be a
non-null pointer to the first element????


Among other things also this.
The above tells you that the array a points to has at least
three elements, i.e. that you can safely access a[0], a[1], a[2].
This can give rise to optimisations and (conversely) the
compiler may give you a diagnostic when you pass a pointer
to an array which is either NULL or does not point to an
array with sufficiently many elements.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 26 '05 #6
Flash Gordon a écrit :
Global (or at least file scope) variable named x and n? Yuk.


I would like to emphasize that.

It is ALWAYS an error to name a GLOBAL variable (i.e. at file or even
process scope) with a name like "n" or "x".

This is bound to provoke name clashes. Who hasn't a local variable
named "x" in a math package somewhere???

Now suppose you mistype the declaration of your x, and istead of writing
int x;
you type
int xc;

The compiler SILENTLY will use the global variable x, that you will
destroy!!!

Today, names can be quite long in C, some compilers accept 256 or even
more characters in a name.

There is a measure in everything, and extremely long names could
be a bore to type, but a global variable should always have a
name that conveys something about its usage, and avoids name clashes.

This is even more necessary in the case of a library like in this example.

If you are writing a LIBRARY, you should do your best to avoid
polluting your user's name space, prefixing all your globals
(if you need globals) with the prefix of your library. Note that
the gsl library always uses gsl_something for its names. I would
ve very surprised if they would leave a variable like 'x'
floatng around... Nobody could use such a library.

jacob
Nov 26 '05 #7

"Skarmander" <in*****@dontmailme.com> wrote
Declaring variables in the innermost block they are used in is good for
readability and may have positive effects on register usage too. In this
case it doesn't buy you much, but it's not hurting anyone either.

I believe in the rule of three.

A human being can cope with three layers of nested parentheses, three levels
of indirection, three dimensions, and three levels of scope.
In C these are global, file scope, and function scope. By adding more levels
you render your program non-human understandable.
Nov 26 '05 #8
Malcolm wrote:
"Skarmander" <in*****@dontmailme.com> wrote
Declaring variables in the innermost block they are used in is good for
readability and may have positive effects on register usage too. In this
case it doesn't buy you much, but it's not hurting anyone either.

I believe in the rule of three.

A human being can cope with three layers of nested parentheses, three levels
of indirection, three dimensions, and three levels of scope.
In C these are global, file scope, and function scope. By adding more levels
you render your program non-human understandable.


I don't have a problem reading other peoples code that uses block scope
variables, but perhaps I am non-human. Sometimes they make it easier to
understand, because you don't have to worry about whether they are used
outside that scope. Having said that, I won't have multiple blocks using
the same name for separate variables, I would prefer either distinct
names or to define than at function scope.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 26 '05 #9
Malcolm wrote:
"Skarmander" <in*****@dontmailme.com> wrote
Declaring variables in the innermost block they are used in is good for
readability and may have positive effects on register usage too. In this
case it doesn't buy you much, but it's not hurting anyone either.


I believe in the rule of three.

A human being can cope with three layers of nested parentheses, three levels
of indirection, three dimensions, and three levels of scope.
In C these are global, file scope, and function scope. By adding more levels
you render your program non-human understandable.

I believe in the rule of seven.

A human being can cope with at most seven items held in active memory
before you have to start referring back to refresh your memory. If, by
putting your variables in subblocks, you can reduce the number of
outstanding variables that have to be kept in active memory at any given
point, you've achieved something.

That said, I've found that very often when people start declaring
variables in subblocks (especially when it's more than one variable)
it's usually time to split the block off to a new function, rather than
trying to keep it all squeezed into one.

S.
Nov 27 '05 #10
jacob navia <ja***@jacob.remcomp.fr> wrote:
There is a measure in everything, and extremely long names could
be a bore to type, but a global variable should always have a
name that conveys something about its usage, and avoids name clashes.


Indeed. We, until recently, had global variables argc and argv (you
read that right) visible to all portions of all modules. It was only
after a number of predictable problems had been caused that this
design faux pas was undone.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 27 '05 #11
Thanks to all for helpful answers about this!
Flash Gordon wrote:
Global (or at least file scope) variable named x and n? Yuk.
Normally I would agree. Originally these variable came as part of a
structure called "state", so the system was referring to state->x,
state->n and state->shuffle. Given the content of the program and how
it's going to be used (as an individually compiled module) it's not a
big deal.

return;


Rather pointless having a return here IMHO.


That came with the GSL and I left it in. return; at the end of a void
function is a matter of preference anyway, right? It doesn't
functionally affect things but some people prefer it for readability.

It's called minimising scope. Because they are declared in the loop you
know, without having to check, that they are not used outside.
Otherwise, you would have to read beyond the end of the loop to see if
the last value gets used outside the loop.


OK. Does it make any difference to the speed at which the code runs?
Let's assume I'm going to be calling this function a LOT so small
differences add up. :-)

Many thanks again for this & all other useful advice.

-- Joe

Nov 27 '05 #12
Christopher Benson-Manica wrote:
We, until recently, had global variables argc and argv (you
read that right) visible to all portions of all modules. It was only
after a number of predictable problems had been caused that this
design faux pas was undone.


How do you go about making variables global with respect to several
modules? I know about using the extern declaration for variables in a
module, but I thought that was generally pretty bad coding practice
because it limits the ability to make the modules stand effectively on
their own.

-- Joe

Nov 27 '05 #13

"Joseph Wakeling" <jo*************@gmail.com> wrote in message
news:11*********************@g47g2000cwa.googlegro ups.com...
Christopher Benson-Manica wrote:
We, until recently, had global variables argc and argv (you
read that right) visible to all portions of all modules. It was only
after a number of predictable problems had been caused that this
design faux pas was undone.


How do you go about making variables global with respect to several
modules? I know about using the extern declaration for variables in a
module, but I thought that was generally pretty bad coding practice
because it limits the ability to make the modules stand effectively on
their own.


There are basically only two ways, i.e., 1. have a defining declaration in
one .c module (i.e., a variable/const placed outside of any function body),
and then access that via extern in other modules - then the linker will
resolve the situation. 2. Use pointers, i.e., have a function in the same
module as the 'static' global that returns the address of variable/const to
a caller - although that rather defeats the purpose I think.

Nov 27 '05 #14

"Flash Gordon" <sp**@flash-gordon.me.uk> wrote in message
news:ef***********@news.flash-gordon.me.uk...
Malcolm wrote:
"Skarmander" <in*****@dontmailme.com> wrote
Declaring variables in the innermost block they are used in is good for
readability and may have positive effects on register usage too. In this
case it doesn't buy you much, but it's not hurting anyone either.

I believe in the rule of three.

A human being can cope with three layers of nested parentheses, three
levels of indirection, three dimensions, and three levels of scope.
In C these are global, file scope, and function scope. By adding more
levels you render your program non-human understandable.


I don't have a problem reading other peoples code that uses block scope
variables, but perhaps I am non-human. Sometimes they make it easier to
understand, because you don't have to worry about whether they are used
outside that scope. Having said that, I won't have multiple blocks using
the same name for separate variables, I would prefer either distinct names
or to define than at function scope.


I'm still a bit 'old school' I'm afraid, and typically declare my variables
at the top of a function - no matter where they're used in that function.

Many years ago, I would have loved having some mechanism that allowed me to
declare them 'nearer' to where they were used - but, then, C wouldn't allow
that. Nowadays, [being an 'old dog' that can't learn 'new tricks'] I stick
with my old habit. However, one thing has improved so much that it's made
things easier, namely, decent IDEs. Years ago, when one only had dumb
editors, it was sometimes really hard to find where things had been
declared/defined. but now, well, I just ask the IDE, and it shows me where a
'thing' is. That's allowed me to learn one new trick however - I no longer
find that hungarian notation is terribly useful.
Nov 27 '05 #15
pemo wrote:

<snip>
I'm still a bit 'old school' I'm afraid, and typically declare my variables
at the top of a function - no matter where they're used in that function.

Many years ago, I would have loved having some mechanism that allowed me to
declare them 'nearer' to where they were used - but, then, C wouldn't allow
that. Nowadays, [being an 'old dog' that can't learn 'new tricks'] I stick
Must be very old school, since it is allowed by C89.
with my old habit. However, one thing has improved so much that it's made
things easier, namely, decent IDEs. Years ago, when one only had dumb
editors, it was sometimes really hard to find where things had been
declared/defined. but now, well, I just ask the IDE, and it shows me where a
'thing' is. That's allowed me to learn one new trick however - I no longer
find that hungarian notation is terribly useful.


I have never found hungarian notation useful.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 27 '05 #16
Joseph Wakeling wrote:
Thanks to all for helpful answers about this!

Flash Gordon wrote:
Global (or at least file scope) variable named x and n? Yuk.


Normally I would agree. Originally these variable came as part of a
structure called "state", so the system was referring to state->x,
state->n and state->shuffle. Given the content of the program and how
it's going to be used (as an individually compiled module) it's not a
big deal.


I stand by my comment. If I had to review that code I would tell you to
go and fix it. After all, some other poor chap may have to maintain that
code.
return;

Rather pointless having a return here IMHO.


That came with the GSL and I left it in. return; at the end of a void
function is a matter of preference anyway, right? It doesn't
functionally affect things but some people prefer it for readability.


Agreed.
It's called minimising scope. Because they are declared in the loop you
know, without having to check, that they are not used outside.
Otherwise, you would have to read beyond the end of the loop to see if
the last value gets used outside the loop.


OK. Does it make any difference to the speed at which the code runs?
Let's assume I'm going to be calling this function a LOT so small
differences add up. :-)


It depends. The only way to find out it to measure on your specific
system. However, my opinion would be that with modern compilers it will
generally make absolutely no difference one way or the other.

If you are concerned with speed the first thing to do is forget it
unless you have a very good reason to think it won't be fast enough.

If you actually do find yourself with a real performance issue, don't
start by looking at the code, start by looking at the algorithm to see
if there is a more efficient algorithm.

My experience is that trying to optimise one function only helps if that
function is very badly written, the compiler is very bad, or you are
doing embedded work and there is a time constraint on that specific
function (e.g. it has to complete during the video blanking period).
Other than those rare cases there is more to be had by improving the
algorithm.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 27 '05 #17

Flash Gordon wrote:
I stand by my comment. If I had to review that code I would tell you to
go and fix it. After all, some other poor chap may have to maintain that
code.
I'm being lazy right now because the chance of anyone else even *using*
that code, let alone maintaining it, are about zero. But you're right.
:-)

My experience is that trying to optimise one function only helps if that
function is very badly written, the compiler is very bad, or you are
doing embedded work and there is a time constraint on that specific
function (e.g. it has to complete during the video blanking period).
Other than those rare cases there is more to be had by improving the
algorithm.


My experience too. But if one is running the same function millions of
times, every little helps... ;-)

Nov 27 '05 #18

"Flash Gordon" <sp**@flash-gordon.me.uk> wrote in message
news:p3************@news.flash-gordon.me.uk...
pemo wrote:

<snip>
I'm still a bit 'old school' I'm afraid, and typically declare my
variables at the top of a function - no matter where they're used in that
function.

Many years ago, I would have loved having some mechanism that allowed me
to declare them 'nearer' to where they were used - but, then, C wouldn't
allow that. Nowadays, [being an 'old dog' that can't learn 'new tricks']
I stick


Must be very old school, since it is allowed by C89.


Um, let's see - can't remember exactly when I started, but it was around
1980 [and I used to be quite good at it then I believe]
with my old habit. However, one thing has improved so much that it's
made things easier, namely, decent IDEs. Years ago, when one only had
dumb editors, it was sometimes really hard to find where things had been
declared/defined. but now, well, I just ask the IDE, and it shows me
where a 'thing' is. That's allowed me to learn one new trick however - I
no longer find that hungarian notation is terribly useful.


I have never found hungarian notation useful.


I had to use it - guess where I used to work!

Nov 27 '05 #19
Joseph Wakeling <jo*************@gmail.com> wrote:
How do you go about making variables global with respect to several
modules?


I spoke poorly there. What I should have said is that our "main"
header file that everything includes used to define these variables as
global. It made for more than its share of headaches.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 28 '05 #20
"pemo" <us***********@gmail.com> writes:
"Flash Gordon" <sp**@flash-gordon.me.uk> wrote in message
news:p3************@news.flash-gordon.me.uk...
pemo wrote:

<snip>
I'm still a bit 'old school' I'm afraid, and typically declare my
variables at the top of a function - no matter where they're used in that
function.

Many years ago, I would have loved having some mechanism that allowed me
to declare them 'nearer' to where they were used - but, then, C wouldn't
allow that. Nowadays, [being an 'old dog' that can't learn 'new tricks']
I stick


Must be very old school, since it is allowed by C89.


Um, let's see - can't remember exactly when I started, but it was around
1980 [and I used to be quite good at it then I believe]


Ok, that's pre-ANSI, but I think it's post-K&R1.

As far as I know, the following was legal even back then:

main()
{
int function_scope_var;
{
int block_scope_var;
}
{
int another_block_scope_var;
}
}

Were you using a compiler that didn't allow it?

(Of course mixing declarations and statements wasn't allowed until C99.)

--
Keith Thompson (The_Other_Keith) 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 30 '05 #21

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

Similar topics

2
by: lallous | last post by:
Hello, In IE, when you redefine a function it will be overwriten by the latest declaration. Is that by the standard or by this browser implementation? -- Elias
3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
134
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that...
8
by: Jim Moon | last post by:
Hi. I'm curious about this syntax: <variable>=function(){...} I'm not finding a definition of this syntax, but I see it used at this website:...
28
by: fred.haab | last post by:
Not having server side scripting, I've been doing this for "last modified" tags on my pages: <div class="modified"> <script type="Text/JavaScript"> <!-- document.write("This page was last...
20
by: svata | last post by:
Hello there, after some time of pondering I come to some solution which would suit me best. Please correct, if I am wrong. Function has two parameters. A string array, better said a pointer to...
1
by: INeedADip | last post by:
What is the difference between: function setupGrid( param ){......} and setupGrid = function( param ){......} Are there any advantages to doing one over the other?
4
by: alex | last post by:
I am so confused with these three concept,who can explained it?thanks so much? e.g. var f= new Function("x", "y", "return x * y"); function f(x,y){ return x*y } var f=function(x,y){
7
by: VK | last post by:
I was getting this effect N times but each time I was in rush to just make it work, and later I coudn't recall anymore what was the original state I was working around. This time I nailed the...
3
by: RobG | last post by:
There has been a discussion on the iPhone web development group where an opinion has been expressed that function expressions are bad for performance and can be avoided by using function...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...

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.