Re: A question on variable defination





sunnylele wrote On 03/31/06 13:11,:
Hi, all,

a question on the following defination:
an external function is defined as:
nmriopen(char *const filename, const int np1, const float step1,
const int np2, const float step2)

what's the difference if it is defined as:
nmriopen(char filename, int np1, float step1,
int np2, float step2)

I assume you mean `char *filename' rather than
`char filename'.

The `const' keyword amounts to a promise (but a weak
one, because it can be circumvented) that the program will
not write to the `const'-qualified object. For your `int'
and `float' arguments, it means that the compiler will
object if you try to change their values within the body
of the function. Such changes cannot affect the caller,
of course, so the "protection" isn't worth much -- but it's
there if you want it.

For the pointer argument things are a little different,
because the thing that is `const' isn't the pointer value
itself, but the thing it points at. (In this case; it's
possible to get the other effect instead, or in addition.)
That *is* a matter of interest to the caller, because the
function has promised (weakly) not to change the contents
of the string the argument presumably points to. The
caller can do things like

char[] myfile = ...;
if (nmriopen(myfile, 1, 0.01, 42, 98.6) < 0)
fprintf(stderr, "nmriopen failed for %s\n",
myfile);

.... without worrying that nmriopen() will change what's in
myfile[] and thus make nonsense of the error message.

and what if use "int *const np1" instead of "const int np1"?

A similar effect: The function promises (weakly) not to
use the pointer `np1' to change the value that it points at.

--
Eric.Sosman@xxxxxxx

.



Relevant Pages

  • Operator overloading, well member function overload in general.
    ... virtual T operator()(float x, float y, float z) const; ... virtual T operator()(int x, int y, int z) const; ... But if I declare it: ...
    (microsoft.public.vc.language)
  • Re: functions arguments
    ... ptr to int** ptr during a series of calls and back again. ... I have to write float but I want it to be flexible here. ... typedef enum Type Type; ... void SetToFive(Type const t,void *const p) ...
    (comp.lang.c)
  • Re: please help with mysterious error....
    ... That depends on your compiler and make system. ... void quit_program(const char *filename, int line) ... "const char *filename" ...
    (comp.lang.c)
  • Re: please help with mysterious error....
    ... void quit_program(char *filename, int line); ... "const char *filename" ... This is saying that the chars being pointed to are const. ...
    (comp.lang.c)
  • Re: cannot read after using strtok()
    ... int main ... //struct loan containts all the loan information retrieved from ... float principle_amt; ... No %s for the filename! ...
    (comp.lang.c)