jotape
jotape

Reputation: 319

Use a #define number into a function in C

Why this code isn't working ? (This is not the actual code, but a simplified version)

#include <stdio.h>
#define NUMBER 5
int function( int NUMBER );

int main (void)
{
    function( NUMBER );
    return 0;

}
int function( int NUMBER )
{
    printf("Hi %d\n", NUMBER);
    return 0;
}

Upvotes: 0

Views: 16072

Answers (5)

Richard Schneider
Richard Schneider

Reputation: 35477

It doesn't work because what you are doing makes no sense. Read the answers above to understand why.

It should be like this:

#include <stdio.h>
#define NUMBER 5

void function ( int );  // a function prototype, saying 'function' accepts an int as the first argument.

int main ( void ) // the 'main' is called when the program runs.
{
   function ( NUMBER );
   return 0;  // returning zero means that no error was encounter in the program
}

void function( int i )
{
   printf ( "Hi %d\n", i );
}

Upvotes: 2

John Bode
John Bode

Reputation: 123448

After preprocessing, your code looks like this:

int function( int 5 );

int main (void)
{
    function( 5 );
    return 0;

}
int function( int 5 )
{
    printf("Hi %d\n", 5 );
    return 0;
}

That is, all occurrences of the symbol NUMBER are replaced with the integer constant 5 before the code is compiled. This works fine in the call to function, but not in the declaration or definition; a parameter name cannot be an integral constant expression.

You will need to change the declaration and definition so that the parameter is not named NUMBER.

Upvotes: 1

Emo Mosley
Emo Mosley

Reputation: 535

The line with int function( int NUMBER ); is a function prototype, yes? You should omit NUMBER in it. Also, your function definition should have its own input variable name - don't use NUMBER, so make it like this:

int function( int num )
{
    printf("Hi\n");
    return 0;
}

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124642

#define NUMBER 5
int function( int NUMBER );

#define is a pre-processor macro, simple text replacement. So, let's look at what you are really trying to compile:

int function( int 5 );

Which makes no sense. This part is fine:

int main (void)
{
    function( NUMBER );
    return 0;    
}

Because you are calling function with the value 5, but the signature of function should look like this:

int function( int x );  // the argument is a variable, x

Upvotes: 10

ouah
ouah

Reputation: 145829

 #define NUMBER 5
 int function( int NUMBER );

is the same as:

 int function( int 5 );

You cannot have a number for a parameter name.

Upvotes: 3

Related Questions