473,320 Members | 2,041 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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 6984
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********@yahoo.com) (cb********@worldnet.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********@worldnet.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********@yahoo.com> writes:
[...]
Never accept advice from ERT. It is akin to quoting Schmidt.


I think you mean Schildt.

--
Keith Thompson (The_Other_Keith) 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_Keith) 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********@yahoo.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********@yahoo.com) (cb********@worldnet.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
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...
4
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
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...
4
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,...
4
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...
23
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
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,...
27
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
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.