sizeof vs #define

In the below example, it seems that sizeof line and #define MAX_LINE will always pass the same value to printf. Is one preferred over the other?

1
2
3
4
5
6
7
8
9
#define MAX_LINE 1024

int main()
{
  char line[MAX_LINE];
  printf("The line size is %d", sizeof line);  

  return 0;
}
Using sizeof with arrays is a little risky, because it can quietly "fail" and return the wrong value if the array is actually a pointer. For example:

1
2
3
4
5
6
7
8
9
10
void func(char line[MAX_LINE])
{
    printf( "The line size is %d", sizeof(line) );  // SURPRISE!
}

int main()
{
    char line[MAX_LINE];
    func( line );
}


This code will not print 1024 like you might expect, but will actually print the size of a pointer (likely either 4 or 8 depending on your system).

For this reason, I tend to avoid using sizeof for arrays. In fact there's a short little function you can write that has the same effect but is safer:

1
2
3
// remove the 'constexpr' if your compiler doesn't support it
template <typename T, int S>
inline constexpr int arraysize(const T (&)[S]) { return S; } 


This will give you the number of elements in an array without falling back on sizeof. Which means if you accidentally call it with a pointer, it will generate a compiler error rather than quietly running and giving you incorrect results.

 
printf("The line size is %d", arraysize(line) );


PS:

Side note: For C++, prefer cout/iostream over printf. Prefer const variables over macros.
Last edited on
Disch wrote:
For C++, prefer cout/iostream over printf. Prefer const variables over macros.

And also!
Prefer std::string over char arrays, and prefer std::vector over other kinds of array.
Topic archived. No new replies allowed.