454,437 Members | 1,337 Online
Need help? Post your question and get tips & solutions from a community of 454,437 IT Pros & Developers. It's quick & easy.

# what is the type of a #define const number

 P: n/a the code is as follows: #include int arr[]={1,2,3,4,5,6,7}; #define size (sizeof(arr)/sizeof(arr[0])) int main() { int index = -1; int x = 0; int t; if( index < size - 1 ) x = arr[index+1]; printf("%d",x); return 0; } then the value of x is 0, not 1. Maybe the type of "index" is promoted to unsigned int ?so the type of "size" is unsigned int?How can I decide the type of a const number by #define macro?Is there anyone can tell me? Thank you! Mar 14 '07 #1
7 Replies

 P: n/a mi*********@gmail.com wrote: the code is as follows: #include int arr[]={1,2,3,4,5,6,7}; #define size (sizeof(arr)/sizeof(arr[0])) int main() { int index = -1; int x = 0; int t; if( index < size - 1 ) x = arr[index+1]; printf("%d",x); return 0; } then the value of x is 0, not 1. Maybe the type of "index" is promoted to unsigned int ?so the type of "size" is unsigned int? Actually, yes. 'sizeof' "returns" size_t, which is unsigned in most implementations. So, promoted to 'size_t', not necessarily unsigned int. "size" gets replaced with "(sizeof(arr)/sizeof(arr[0]))", so by the time there are any types in the program, there is no "size"... >How can I decide the type of a const number by #define macro?Is there anyone can tell me? Any macro just substitutes one expression with another. You need to see what your code looks like after preprocessing to understand what your expression looks like and what type it has. V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask Mar 14 '07 #2

 P: n/a On Mar 14, 6:17 pm, "Victor Bazarov" int arr[]={1,2,3,4,5,6,7}; #define size (sizeof(arr)/sizeof(arr[0])) int main() { int index = -1; int x = 0; int t; if( index < size - 1 ) x = arr[index+1]; printf("%d",x); return 0; } then the value of x is 0, not 1. Maybe the type of "index" is promoted to unsigned int ?so the type of "size" is unsigned int? Actually, yes. 'sizeof' "returns" size_t, which is unsigned in most implementations. So, promoted to 'size_t', not necessarily unsigned int. "size" gets replaced with "(sizeof(arr)/sizeof(arr[0]))", so by the time there are any types in the program, there is no "size"... How can I decide the type of a const number by #define macro?Is there anyone can tell me? Any macro just substitutes one expression with another. You need to see what your code looks like after preprocessing to understand what your expression looks like and what type it has. V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask The disadvantage of macro is that it doesnot follow the strict type checking To run the code, write the statement as #define size (int)(sizeof(arr)/sizeof(arr[0])) OR if( index < int(size - 1) ) Mar 14 '07 #3