Why is using a constant considered a better programming style than using a literal?

Why is using a constant considered a better programming style than using a literal? What is the exact advantage of the previous compared to the last?

+3
source share
6 answers

One reason is to help with maintenance. Let's say you are stuck in the dark ages, and your graphic manipulation program only works with 1.4 M. floppy disks.

You get a request to work with the new 2.8M flash drives, and you think about yourself: "Ha, I just need to find the code looking for 1440 and replace it with 2880. Simple, huh?"

, , 1440 , , , - . D'Oh!

, 1440 .

:

#define TWIPS_PER_INCH 1440
#define DISK_SZ 1440

, , .

, . .

, , , - -1, 0 1 - , :-) , , .

, , , , :

#define SEVENTY_TWO 72

, , , , 72 ( ).


- . , , 1.414. SQR_ROOT_OF_2, , . , :

SECS_PER_DAY      86400
CUST_ADDR_LINES   7
INVALID_ID        -1
DAYS_PER_CENTURY  36524
PASS_LEVEL        63
MIN_REPUTATION    10000
MAX_LOAN_AMT      200000

, , , , ?

+13

, .

:

x = 3.14 * 3 ^ 2;

x = PI * RADIUS ^ 2;

-, " ", - . , .

+2

- . , . , - .

, , .

+1
  • , , . , , . , . , , , .
  • . , if (m > MONTHS_PER_YEAR), if (m > 12), , m . ( , , MONTHS_PER_YEAR, m "", 12 ).
  • PI, ( "" , ).
+1

, , , . , #define SEVENTY_TWO 72, , .

0

" ". , , , , -, .

:

x = y * 100 / 2;

x = y * 50;

-, , , ?

:

x = y * CENTS_IN_DOLLAR / NO_OF_PARKING_METERS;

, y , ( ).

, , : , , , . - , , , .

, , "".

0

Source: https://habr.com/ru/post/1778437/


All Articles