Finding the PATH_MAX

Your code may be compiled on a PC, Mac, Linux system, or even some microcontroller. In each case, it helps to know the environment before you code. You can guess, but it’s better to use the defined constants — if they’re available to you.

What do you do when a constant isn’t available? Actually, what’s more important is being able to check whether or not a constant exists. To manage that feat, you use the preprocessor directives: #ifdef, #else, and #endif.

If you’re just starting out with C coding, you probably haven’t used preprocessor directives beyond #include and the occasional #define. The if-else series of directives are easy to understand, providing you have a general concept of the if-else programming thing.

As a real-life example, consider the constant PATH_MAX. It’s determines how many characters are allowed in a full pathname. The value differs between the various operating systems, so it’s best to use PATH_MAX to set the buffer size for pathnames, as opposed to just guessing.

To confirm that the PATH_MAX constant is defined, use the #ifdef directive:

#ifdef PATH_MAX

When PATH_MAX is defined, the statements following #ifdef are compiled.

When PATH_MAX isn’t defined, the #else directive takes over. The statements following #else are compiled when PATH_MAX is undefined.

The #endif directive closes the decisions structure. It’s traditionally followed by a comment identifying the constant.

The following code represents a real-life example of testing for the PATH_MAX constant, which should be defined in the limits.h header file:

#include <stdio.h>
#include <limits.h>

int main()
{

#ifdef PATH_MAX
    printf("PATH_MAX is defined as %d.\n",PATH_MAX);
#else
    printf("PATH_MAX isn't defined on this system.\n");
#endif /* PATH_MAX */

    return(0);
}

When the PATH_MAX variable is defined, the first printf() statement is compiled, otherwise the second one is compiled. Remember, preprocessor directives don’t execute when the program runs; they simply tell the compiler which part of the code to include in the final program.

Here’s the output for my Macintosh:

PATH_MAX is defined as 1024.

Here’s the output on my PC:

PATH_MAX is defined as 260.

The differing values justify why using a constant like PATH_MAX is important. The alternative would be to guess and specify a “safe” value for the constant. That’s a valid option only when you’ve tried testing for a constant as shown in this Lesson’s sample code.