Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Can we use sizeof() operator in preprocessor directives ? (C language)

Status
Not open for further replies.

rameshbabu

Member level 2
Member level 2
Joined
Aug 1, 2007
Messages
46
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,286
Activity points
1,663
Can we use sizeof() operator in preprocessor directives.

#include<stdio.h>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))

int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
why there is no output for this program.
 

Re: C

yep, you can. You have to see a #define as some text that will be substituted BEFORE compiling (that's why they're called PRE-processor directives)

#define MYWORD ANYTEXTIWANT

then all text like "MYWORD" found along the code will be substituted by "ANYTEXTIWANT" before compiling, so what the compiler will have tu understand is "ANYTEXTIWANT"...

conclusion: you can make any define you want, but keep in mind that the text you substitute will have to have sense in the code piece it's inserted

good luck

EDIT:
why there is no output for this program.
Sorry, i just read the question.

It's very strange... i've tried it and as you said, there is no output, but if you do this, there is:

Code:
#include <stdio.h>

#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))

int array[] = {23,34,12,17,204,99,16};

int main()
{
  int d,sz;

  for( d=-1, sz=(TOTAL_ELEMENTS-2); d<=sz; d++)
    printf("%d\n",array[d+1]);

  return 0;
}

Anyways, i have to say, it's a weird way of representing an array... why don't you go from d=0 to d=N-1 ?
 

C

I tried it and it works ok using Borland Tubo C
 

Re: C

CMIIW,

sizeof() operator returns type of size_t, so maybe you have to convert the type to int, like

(int) sizeof(array)

one other thing is that macros simply replace the text, so you must be careful with precedence. if

#define DOUBLE(x) 2*x

then

DOUBLE(MyVar-1)

will be replaced by

2*MyVar-1

which won't be what it meant to be. The safe way is to enclose every constants and parameter with brackets,

#define DOUBLE(x) ((2)*(x))

so the same call will be replaced by

((2)*(MyVar-1))

I hope this helps, and sorry if there's any mistake.
 

Re: C

I am also obseving the same thing.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top