Hour 23 : Compiling Programs: The C Preprocessor

Example 23.1, Page No 394

In [9]:
METHOD = "ABS"
def ABS(val):
    if val < 0:
        return -(val)
    else:
        return (val)
MAX_LEN = 8
NEGATIVE_NUM = -10
array = range(MAX_LEN)
print "The orignal values in array:"
for i in range(MAX_LEN):
    array[i] = (i + 1) * NEGATIVE_NUM;
    print "array[",i,"]:",array[i]
print "\nApplying the ",METHOD," macro:\n"
for i in range(MAX_LEN):
    print "ABS(%d) : "%(array[i]), ABS(array[i])
The orignal values in array:
array[ 0 ]: -10
array[ 1 ]: -20
array[ 2 ]: -30
array[ 3 ]: -40
array[ 4 ]: -50
array[ 5 ]: -60
array[ 6 ]: -70
array[ 7 ]: -80

Applying the  ABS  macro:

ABS(-10) :  10
ABS(-20) :  20
ABS(-30) :  30
ABS(-40) :  40
ABS(-50) :  50
ABS(-60) :  60
ABS(-70) :  70
ABS(-80) :  80

Example 23.2, Page No 398

In [13]:
#There is no concept of the mentioned directives in Python.
UPPER_CASE = True
LOWER_CASE = False
if UPPER_CASE:
    print "THIS LINE IS PRINTED OUT,\n"
    print "BECAUSE UPPER_CASE IS DEFINED.\n"
if not LOWER_CASE:
    print "\nThis line is printed out,\n"
    print "because LOWER_CASE is not defined.\n"
THIS LINE IS PRINTED OUT,

BECAUSE UPPER_CASE IS DEFINED.


This line is printed out,

because LOWER_CASE is not defined.

Example 23.3, Page No 401

In [5]:
C_LANG = 'C'
B_LANG = 'B'
NO_ERROR = 0
if C_LANG == 'C' and B_LANG == 'B':
    del C_LANG
    C_LANG = "I only know C language.\n"
    print C_LANG
    del B_LANG
    B_LANG = "I know BASIC.\n"
    print C_LANG,B_LANG
elif C_LANG == 'C':
    del C_LANG
    C_LANG = "I only know C language.\n"
    print C_LANG
elif B_LANG == 'B':
    del B_LANG
    B_LANG = "I only know BASIC.\n"
    print B_LANG
else:
    print "“I don’t know C or BASIC.\n"
I only know C language.

I only know C language.
I know BASIC.

Example 23.4, Page No 403

In [9]:
ZERO = 0
ONE = 1
TWO = ONE + ONE
THREE = ONE + TWO
TEST_1 = ONE
TEST_2 = TWO
TEST_3 = THREE
MAX_NUM = THREE
NO_ERROR = ZERO
def StrPrint(ptr_s,max1):
    for i in range(max1):
        print "Content: ",ptr_s[i],"\n"

str1 = ["The choice of a point of view","is the initial act of culture.","--- by O. Gasset"]
if TEST_1 == 1:
    if TEST_2 == 2:
        if TEST_3 == 3:
            StrPrint(str1,MAX_NUM)
        else:
            StrPrint(str1,MAX_NUM - ONE)
    else:
        StrPrint(str1,MAX_NUM - ONE)
else:
    "No TEST macro has been set.\n"
Content:  The choice of a point of view 

Content:  is the initial act of culture. 

Content:  --- by O. Gasset