Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbolic constants in C (#define statement)

Tags:

c

After reading through some of K&R's The C Programming Language I came across the #define symbolic constants. I decided to define...

#define INTEGER_EXAMPLE 2
#define CHAR_EXAMPLE 2

...so my question is how does C know if I'm defining an int or a char type?

like image 577
CS Student Avatar asked Nov 29 '22 12:11

CS Student


2 Answers

#define-d names have no types. They just define textual replacements.

What the compiler is seeing is the preprocessed form. If using GCC, try gcc -C -E somesource.c and have a look at the (preprocessed) output.

In the 1980s the preprocessor was a separate program.

Read about the cpp preprocessor, and preprocessor and C preprocessor wikipages.

You could even define ill-defined names like

#define BAD @*?$ some crap $?

And even more scary you can define things which are syntactically incomplete like

#define BADTASTE 2 +

and later code BADTASTE 3

Actually, you want to use parenthesis when defining macros. If you have

#define BADPROD(x,y) x*y

then BADPROD(2+3,4+5) is expanded to 2+3*4+5 which the compiler understands like 2+ (3*4) +5; you really want

#define BETTERPROD(x,y) ((x)*(y))

So that BETTERPROD(2+3,4+5) is expanded to ((2+3)*(4+5))

Avoid side-effects in macro arguments, e.g. BETTERPROD(j++,j--)

In general, use macros with care and have them stay simple.

like image 190
Basile Starynkevitch Avatar answered Dec 05 '22 03:12

Basile Starynkevitch


Regarding these defines, it doesn't, the expanded macros doesn't have a type. The pre-processor which processes the #define is just replacing text within the source code

When you use these defines somewhere, e.g.

int i = INTEGER_EXAMPLE;

This will expand to

int i = 2;

Here the literal 2 (which in this context is an int) is assigned to an int.

You could also do:

char c = INTEGER_EXAMPLE;

Here too, the literal 2 is an int, and it is assigned to a char. 2 is within the limits of a char though, so all is ok.

You could even do:

int INTEGER_EXAMPLE = 2;

This would expand to

int 2 = 2;

Which isn't valid C.

like image 29
nos Avatar answered Dec 05 '22 01:12

nos