Magic Number in C
×


Magic Number in C

253

 Magic numbers in C programming are constant values used directly in the code without explanation, which may make the code harder to understand and maintain.

 It's considered a best practice to avoid magic numbers by assigning them to named constants with descriptive names.


Steps:

 Identify Magic Numbers: Look for numeric literals directly embedded in code that lack clear meaning or explanation.

 Assign to Constants: Replace magic numbers with named constants defined using #define or const keywords to give them descriptive names.

 Use Descriptive Names: Choose meaningful names for constants that convey their purpose in the code.

1Program Using Constants to Replace Magic Numbers

// Program using constants to replace magic numbers
#include<stdio.h> 

#define PI 3.14159

int main() {
    double radius = 5.0;
    double area = PI * radius * radius;

    printf("Area of the circle: %f\n", area);

    return 0;
}

Output:

Area of the circle: 78.539750

2Program Avoiding Magic Numbers with Constants

// Program for avoiding magic numbers with constants
#include<stdio.h> 

#define MAX_LENGTH 100

int main() {
    char username[MAX_LENGTH];
    char password[MAX_LENGTH];

    printf("Enter username: ");
    scanf("%s", username);

    printf("Enter password: ");
    scanf("%s", password);

    // Authentication logic

    return 0;
}

Output:

Enter username: siya
Enter password: 4567

3Program Using Constants for Code Clarity

// Program for using constants for code clarity
#include<stdio.h> 

#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTE 60

int main() {
    int days = 7;
    int total_seconds = days * HOURS_IN_DAY * MINUTES_IN_HOUR * SECONDS_IN_MINUTE;

    printf("Total seconds in a week: %d\n", total_seconds);

    return 0;
}

Output:

Total seconds in a week: 604800


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments