473,761 Members | 3,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to use #define and When to use const?

I'm not very clear about when to use #define and when to use const?

#define number 4
const int number = 4;

If I just want to define a global constant, which way of the above is
better?

Thanks,
Peng
Nov 14 '05 #1
7 7008
Peng Yu wrote:
I'm not very clear about when to use #define and when to use const?

#define number 4
const int number = 4;

If I just want to define a global constant,
which way of the above is better?
const int number = 4;

is better.
cat main.c #include <stdio.h>

const size_t n = 128;

int main(int argc, char* argv[]) {
int array[n];
for (size_t j = 0; j < n; ++j)
array[j] = j;
return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c

Nov 14 '05 #2
>I'm not very clear about when to use #define and when to use const?

#define number 4
const int number = 4;

If I just want to define a global constant, which way of the above is
better?


If you want a constant expression (e.g. suitable for use with 'case'
or C89 array dimensions), use the #define. If you use the const
int number = 4; declaration, number is *NOT* a constant expression.

The declaration:

ant const int number = 4;

is no longer valid since someone fooling around with undefined
behavior from fflush(stdin) removed it from the standard retroactively :-)

Gordon L. Burditt

Nov 14 '05 #3
"E. Robert Tisdale" wrote:
Peng Yu wrote:
I'm not very clear about when to use #define and when to use const?

#define number 4
const int number = 4;

If I just want to define a global constant,
which way of the above is better?


const int number = 4;

is better.


This is misinformation. In C the declaration "const int number =
4;" simply creates a variable that is expected to be read-only (but
which can be altered). The way to get a constant usable where
constant expressions are needed (such as the size of an array) is
with a #define.

Never accept advice from ERT. It is akin to quoting Schmidt.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #4
In article <41************ ***@yahoo.com>
CBFalconer <cb********@wor ldnet.att.net> wrote:
... In C the declaration "const int number = 4;" simply creates a
variable that is expected to be read-only (but which can be altered).
Well, more precisely, it *may* be alterable, but if you try to do so,
the effect is undefined. In any case, it is indeed still a variable,
even if it never varies.
The way to get a constant usable where constant expressions are
needed (such as the size of an array) is with a #define.


This is the most general method, and the one most C programmers use.

For the specific case of "int"-valued constants, you can (mis)use
enum:

enum { number = 4 };

makes "number" an integer constant, of type "int" and value 4. This
can be used in those places that require constants, such as in
sizing arrays -- even those outside a function, or any in C89 --
or in "case" labels:

switch (func()) {

case 1:
... code for "case 1" ...
break;

case number:
... code for "case 4" ...
break;

default:
... code for other cases ...
break;
}

A "const int" is not suitable for any of those three:

% cat t.c
const int number = 4;
char foo[number];
% cc -std=c89 -pedantic -Wall -W -O -c t.c
t.c:2: warning: ISO C89 forbids variable-size array `foo'
t.c:2: variable-size type declared outside of any function
% cc -std=c99 -pedantic -Wall -W -O -c t.c
t.c:2: variable-size type declared outside of any function

% cat t2.c
enum { number = 4 };
char foo[number];
% cc -std=c89 -pedantic -Wall -W -O -c t2.c
% cc -std=c99 -pedantic -Wall -W -O -c t2.c

The "enum" method works; the "const" method does not. (I prefer
the "#define" over the "enum" myself, and "enum" does not allow
defining floating-point constants, or constants of unsigned, long,
or -- in C99 -- long long types.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5
CBFalconer <cb********@yah oo.com> writes:
[...]
Never accept advice from ERT. It is akin to quoting Schmidt.


I think you mean Schildt.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > writes:
Peng Yu wrote:
I'm not very clear about when to use #define and when to use const?
#define number 4
const int number = 4;
If I just want to define a global constant, which way of the above
is better?


const int number = 4;

is better.
> cat main.c

#include <stdio.h>

const size_t n = 128;

int main(int argc, char* argv[]) {
int array[n];
for (size_t j = 0; j < n; ++j)
array[j] = j;
return 0;
}
> gcc -Wall -std=c99 -pedantic -o main main.c


That is of course illegal in C90.

In C99, if I'm not mistaken, the array is actually a VLA (Variable
Length Array), something not supported in C90. Even though n is
declared "const", it's not a "constant expression".

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #7
Keith Thompson wrote:
CBFalconer <cb********@yah oo.com> writes:
[...]
Never accept advice from ERT. It is akin to quoting Schmidt.


I think you mean Schildt.


Thanks for the correction. Apologies to all the worlds Schmidts.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2557
by: John Ratliff | last post by:
Let's say I had a program which uses some constants. Would it be "better" to declare them like this: #ifndef __MY_HDR_FILE #define __MY_HDR_FILE #define STRING_CONST "some string..." #define INT_CONSTANT 4852 #endif
4
2068
by: Alex Vinokur | last post by:
Hi, The code below has no problem with GNU g++ 3.3, but it has a problem with GNU g++ 3.4. Any suggestions? ------ foo.cpp ------ #include <vector> using namespace std;
14
10357
by: Rajan | last post by:
Hi All C++ Experts (1)I want have a simple suggestion from u all experts which is preferable const or #define and in which cases (2)in my project i want to avoid hardcoding , for that i have defined macros in my header files. but we have coding rules that says "use const for avoiding hardcoding".My question is that "what will be the difference in terms of memory for Const vs # Define"
4
2505
by: QQ | last post by:
Hello I am a newbie on network programming. I am trying to receive a packet if((numbytes = recvfrom(udp_fd1, buf, MAXLEN-1, 0,(struct sockaddr*)&register_addr, &addr_len))==-1){ fprintf(stderr, "error in recvfrom.\n"); exit(1); } The packet I am receiving has the following possible structure.
4
2779
by: yancheng.cheok | last post by:
Recently, I try to replace #define with const in header file. However, there are concerns on, multiple const object will be created, if the header file is included in multiple cpp files. For example: In version.h ------------ #ifndef VERSION #define VERSION
23
3919
by: anon.asdf | last post by:
Hello! In the following code-snippet, is it possible to initialize each element of arr, with STRUCT_INIT? struct mystruct { int a; char b; };
6
2166
by: wongjoekmeu | last post by:
I need to rewrite some typedef to #define. For instance I rewrote typedef void* handle to #define handle void* But I saw for instance another typedef in my code which I don't understand, which is
27
5421
by: pereges | last post by:
I need to define the plancks constant 6.67 X 10 exp -34. Is it possible to do it using #define or would you suggest using a (static ?)const double.
1
5225
by: sophia | last post by:
Dear all, the following are the differences b/w #define and typedef ,which i have seen in Peter van der lindens book. is there any other difference between thes two ? The right way to think about typedef as being a complete encapsulated type - you can't add to it after you have declared it.
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9377
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9989
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8814
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.