Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do most C developers use define instead of const? [duplicate]

In many programs a #define serves the same purpose as a constant. For example.

#define FIELD_WIDTH 10 const int fieldWidth = 10; 

I commonly see the first form preferred over the other, relying on the pre-processor to handle what is basically an application decision. Is there a reason for this tradition?

like image 656
C. Ross Avatar asked Oct 26 '10 13:10

C. Ross


People also ask

What is the advantage of #define over const?

The big advantage of const over #define is type checking. #defines can't be type checked, so this can cause problems when trying to determine the data type. If the variable is, instead, a constant then we can grab the type of the data that is stored in that constant variable.

Why do you use #define in C?

#define is a preprocessor directive that is used to define macros in a C program. #define is also known as a macros directive. #define directive is used to declare some constant values or an expression with a name that can be used throughout our C program.

When to use #define vs const?

const and #define both are used for handle constants in source code, but they few differences. #define is used to define some values with a name (string), this defined string is known as Macro definition in C, C++ while const is a keyword or used to make the value of an identifier (that is constant) constant.

What is the advantages of #define?

the benefit of using define is once you define the variable for exp: #define NUMBER 30, all the code in main will use that code with value 30. If you change the 30 to 40 it will directly change all value in main which using this variable (NUMBER).


1 Answers

There is a very solid reason for this: const in C does not mean something is constant. It just means a variable is read-only.

In places where the compiler requires a true constant (such as for array sizes for non-VLA arrays), using a const variable, such as fieldWidth is just not possible.

like image 141
Bart van Ingen Schenau Avatar answered Oct 20 '22 12:10

Bart van Ingen Schenau