Re: #define....



> sizeof gets the number of items in an array,

No.

The sizeof statement gives a size of its argument in bytes. If the array
contains long integers, sizeof returns the number of items multiplied by
four, because every long integer occupies four bytes of memory.

In order to get the number of items, you have to divide the size of the
table by the size of its any element. The "dim" macro divides the size of
the table by the size of its first element (arrays indices start from 0 in
C/C++), thus providing the number of items in the array (NOT its size).


> but what about the
> "dim(x)" whats that doing there?
> And furthermore, "x" is nowhere to be found in the program example.

You have to understand how the C compiler works.

Before the code is compiled, it is precompiled, and if your code contains a
line:
#define something(x) something_else(x)

then the precompiler will exchange any occurrence of the text
"something(...)", where "..." is an expression (i.e. constant, variable
name, function call, etc.) with "something_else(...)".

For instance, the code:
int i = 5;
int j = something(i);

will be changed to the code:
int i = 5;
int j = something_else(i);

After the precompiler stops its work, the real compiler starts. It reads and
compiles the source changed by the precompiler.


OK. Let's go back to our "dim".

In this case, the following code:
long t[50];
int i = dim(t);

will be exchanged by the precompiler to:
long t[50];
int i = sizeof(t)/sizeof(t[0]);

according to the #define directive.

No wonder you cannot find 'dim' in the docs, it is not a standard function,
it is just a directive for the precompiler in this particular source file.

Hope this clarifies something.

DW.


.



Relevant Pages

  • Re: Sorting Array of Structures
    ... You had written qsort(book, sizeof(book) / sizeof ... ] int hold; ... given the declarations of book (an array of N LIBRARY objects) and ...
    (comp.lang.c)
  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)
  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)
  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)
  • (patch for Bash) regex case statement
    ... Following up on my previous patch for regex conditional tests, ... /* Return an array of strings; ... int dollarflag, zeropad, compareflag; ... SHELL_VAR *var; ...
    (comp.unix.shell)