Thread: How preprocessor works

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    27

    How preprocessor works

    I thought I knew how the preprocessor worked until I ran until a recent problem.

    Say I have the declaration below:

    Code:
    #define INFILE dataset
    then later in my main function I have

    Code:
    FILE *fptr;
    int p;
    fptr = fopen("INFILE","r");
    fscanf(fptr," %d",&p);
    the file "dataset" exists with the number 5 in it.

    However when I run this I get a segmentation fault. So I'm thinking the preprocessor doesn't replace INFILE with dataset which I thought it did.

    Can anybody explain to me what's going on?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The preprocessor does not make substitutions from within strings.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I think you want
    Code:
    #define INFILE "dataset"
    fptr = fopen(INFILE,"r");
    Without the quotes, dataset would be considered to refer to another variable, eg
    Code:
    int mynum;
    #define XXX mynum
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed