473,799 Members | 3,350 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Constant Expressions in C

Consider this example:

u8 my_array[10];

for (i = 0; i < (sizeof(my_arra y)/sizeof(u8)); i++) {
...
}

In the standard C specification, is the evaluation of
'(sizeof(my_arr ay)/sizeof(u8))' to 10 guarenteed to happen at compile
time? Or is it a compiler optimization? From what I have read, it
looks like it is a compiler optimization, but I would like to get
confirmation.

Now if is not guarenteed to happen at compile time, is it better to do
something like the following:

const u8 my_array_size = (sizeof(my_arra y)/sizeof(u8));

to guarentee that you are not doing a divide a run time? On the
systems I have worked on, divides take a very long time. However,
almost every compiler that I have dealt with does the evaluation at
compile time.

Apr 20 '07 #1
15 2913
On Apr 20, 11:33 pm, skibud2 <mike.hallo...@ gmail.comwrote:
Now if is not guarenteed to happen at compile time, is it better to do
something like the following:

const u8 my_array_size = (sizeof(my_arra y)/sizeof(u8));

to guarentee that you are not doing a divide a run time? On the
systems I have worked on, divides take a very long time. However,
almost every compiler that I have dealt with does the evaluation at
compile time.
Just curious: Which compiler didn't?

Apr 20 '07 #2

"skibud2" <mi***********@ gmail.comwrote in message
news:11******** **************@ o5g2000hsb.goog legroups.com...
Consider this example:

u8 my_array[10];

for (i = 0; i < (sizeof(my_arra y)/sizeof(u8)); i++) {
...
}

In the standard C specification, is the evaluation of
'(sizeof(my_arr ay)/sizeof(u8))' to 10 guarenteed to happen at compile
time? Or is it a compiler optimization? From what I have read, it
looks like it is a compiler optimization, but I would like to get
confirmation.

Now if is not guarenteed to happen at compile time, is it better to do
something like the following:

const u8 my_array_size = (sizeof(my_arra y)/sizeof(u8));

to guarentee that you are not doing a divide a run time? On the
systems I have worked on, divides take a very long time. However,
almost every compiler that I have dealt with does the evaluation at
compile time.
Effectively you are guaranteed that the compiler will evaluate constant
expressions at compile time. The standard doesn't specify any particular
sequence of machine code instructions as long as the behaviour is correct,
because it was decided not to try impose performance requirements at all.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Apr 20 '07 #3
skibud2 wrote:
Consider this example:

u8 my_array[10];

for (i = 0; i < (sizeof(my_arra y)/sizeof(u8)); i++) {
...
}

In the standard C specification, is the evaluation of
'(sizeof(my_arr ay)/sizeof(u8))' to 10 guarenteed to happen at compile
time? Or is it a compiler optimization? From what I have read, it
looks like it is a compiler optimization, but I would like to get
confirmation.
sizeof(my_array )/sizeof(u8) is required to be a compile time constant,
consider

int my_array[10];
int other[sizeof(my_array )/sizeof(int)];
Now if is not guarenteed to happen at compile time, is it better to do
something like the following:

const u8 my_array_size = (sizeof(my_arra y)/sizeof(u8));
Better in the sense it makes the code easier to read.

--
Ian Collins.
Apr 21 '07 #4
On 20 Apr 2007 15:33:36 -0700, skibud2 <mi***********@ gmail.comwrote
in comp.lang.c:
Consider this example:

u8 my_array[10];

for (i = 0; i < (sizeof(my_arra y)/sizeof(u8)); i++) {
...
}

In the standard C specification, is the evaluation of
'(sizeof(my_arr ay)/sizeof(u8))' to 10 guarenteed to happen at compile
time? Or is it a compiler optimization? From what I have read, it
looks like it is a compiler optimization, but I would like to get
confirmation.

Now if is not guarenteed to happen at compile time, is it better to do
something like the following:

const u8 my_array_size = (sizeof(my_arra y)/sizeof(u8));
I wouldn't do this, C is not C++. If you define this at file scope,
it has external linkage and the compiler must actually create the
object, because it cannot tell whether another translation unit will
refer to it by name.

Even if you define it as static, some C compilers will create the
object and read its value when you use it in an expression.
to guarentee that you are not doing a divide a run time? On the
systems I have worked on, divides take a very long time. However,
almost every compiler that I have dealt with does the evaluation at
compile time.
Despite what others have said, the C language standard does not
require a compiler to evaluate constant expressions at compile time
unless it needs to use the value at compile time, as in Ian's example
of using it to define the size of an array.

Another such case would be where an integer constant is used as a case
value in a switch statement.

In this particular case, it makes much more sense to define the value
ahead of time and use it both for defining the array and when you need
the number of its elements:

#define MY_ARRAY_SIZE /* some value */

u8 my_array [MY_ARRAY_SIZE];

In the general case, you are better off using a nameless enum, so long
as the value fits in the range of an int:

enum { my_array_size = sizeof my_array / sizeof *my_array };

This will be evaluated at compile time and not create an object at run
time.

Also note that in general, the expression for the number of elements
should make use of the explicit conversion of an array name to a
pointer, and using that to access the type of the members:

elements = sizeof array_name / sizeof *array_name;

If you ever decide that you need to change the type, say to int or
long, you don't have to hunt down and make sure you change all the
sizeof expressions.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Apr 21 '07 #5
Jack Klein wrote:
>
Despite what others have said, the C language standard does not
require a compiler to evaluate constant expressions at compile time
unless it needs to use the value at compile time, as in Ian's example
of using it to define the size of an array.
Thanks for the clarification Jack, I wasn't aware of that "unless".

--
Ian Collins.
Apr 21 '07 #6
skibud2 wrote:
>
Consider this example:

u8 my_array[10];

for (i = 0; i < (sizeof(my_arra y)/sizeof(u8)); i++) {
...
}

In the standard C specification, is the evaluation of
'(sizeof(my_arr ay)/sizeof(u8))' to 10 guarenteed to happen at compile
time? Or is it a compiler optimization? From what I have read, it
looks like it is a compiler optimization, but I would like to get
confirmation.

Now if is not guarenteed to happen at compile time, is it better to do
something like the following:

const u8 my_array_size = (sizeof(my_arra y)/sizeof(u8));

to guarentee that you are not doing a divide a run time? On the
systems I have worked on, divides take a very long time. However,
almost every compiler that I have dealt with does the evaluation at
compile time.
You currently engaged in premature microoptimizati on.
The compiler may evaluate the constant expression
either at compile time or during run time.
Constant expressions of integer type
are commonly evaluated at compile time.
Either of the two ways of coding that you've shown
could be slower or faster.

If (sizeof array / sizeof array[0]) is evaluated at compile time,
then there's a chance that comparing
i < compile_time_co nstant
might be faster than
i < run_time_variab le

--
pete
Apr 21 '07 #7
On Apr 21, 11:37 am, pete <pfil...@mindsp ring.comwrote:
If (sizeof array / sizeof array[0]) is evaluated at compile time,
then there's a chance that comparing
i < compile_time_co nstant
might be faster than
i < run_time_variab le
On the other hand, a constant might also be slower than a runtime
variable. (And I do have real examples for this, where a construct
like

static int s_one = 1;
int one = s_one;

and using "one" instead of "1" with a particular compiler led to
significantly faster code. )

Apr 21 '07 #8
On Apr 21, 9:35 am, "christian. bau" <christian....@ cbau.wanadoo.co .uk>
wrote:
On Apr 21, 11:37 am, pete <pfil...@mindsp ring.comwrote:
If (sizeof array / sizeof array[0]) is evaluated at compile time,
then there's a chance that comparing
i < compile_time_co nstant
might be faster than
i < run_time_variab le

On the other hand, a constant might also be slower than a runtime
variable. (And I do have real examples for this, where a construct
like

static int s_one = 1;
int one = s_one;

and using "one" instead of "1" with a particular compiler led to
significantly faster code. )
<OT>

That really surprises me. And 'significantly' faster? that's puzzling.
Mostly small integer constants (that can fit in, say 16 bits) are
directly
encoded in the same machine instruction. Thus no load/store for the
operand.
So I'm wondering why any compiler would ever do things slowly on using
a literal '1'
than using thru' a variable (named like one above).

</OT>

Karthik

Apr 21 '07 #9
"ka*****@gmail. com" <ka*****@gmail. comwrites:
On Apr 21, 9:35 am, "christian. bau" <christian....@ cbau.wanadoo.co .uk>
wrote:
>On Apr 21, 11:37 am, pete <pfil...@mindsp ring.comwrote:
If (sizeof array / sizeof array[0]) is evaluated at compile time,
then there's a chance that comparing
i < compile_time_co nstant
might be faster than
i < run_time_variab le

On the other hand, a constant might also be slower than a runtime
variable. (And I do have real examples for this, where a construct
like

static int s_one = 1;
int one = s_one;

and using "one" instead of "1" with a particular compiler led to
significantl y faster code. )

<OT>
That really surprises me. And 'significantly' faster? that's puzzling.
Mostly small integer constants (that can fit in, say 16 bits) are
directly
encoded in the same machine instruction. Thus no load/store for the
operand.
So I'm wondering why any compiler would ever do things slowly on using
a literal '1'
than using thru' a variable (named like one above).
Machine instructions still have to be loaded from memory; "one" could
have been stored in a register. (That's pure speculation, off the top
of my head.)
</OT>
--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Apr 22 '07 #10

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

Similar topics

2
1816
by: JJ Feminella | last post by:
This statement is legal C#: public const string day = "Sunday"; but this statement is not: public const string days = new string { "Sun", "Mon", "Tue" }; The C# Programmer's Reference specifies that 'the only valid values of a constant declarator constant expressions'. A constant expression is defined as 'an expression that can be fully evaluated at compile-time ... Therefore, the only possible values for constants of reference...
13
2575
by: devdatta_clc | last post by:
Hi C experts I've a bunch of questions. Consider this simplified piece of code. const int a = 10; int main () { static int b = a;
6
2838
by: niklaus | last post by:
Hi, I have seen that the following code compiles in some environments like devc++ but fails on some env's like gcc on linux. Can someone tell if "int *au=malloc(sizeof(int)*10);" is a constant expression and can be used in global namespace/file scope. Which part of the standard says or describes this . #include<stdio.h> #include<stdlib.h>
7
10212
by: Paul Edwards | last post by:
On ecgs (gcc) 2.91.57 and on gcc 3.2.3 I am getting the error "initializer element is not constant" on the below code. The code compiles fine with other compilers I have. Is this valid C89 code? extern int *b; int *a = b; int main(void)
13
27442
by: hn.ft.pris | last post by:
Hi: I have the following simple program: #include<iostream> using namespace std; int main(int argc, char* argv){ const double L = 1.234; const int T = static_cast<const int>(L); int arr;
13
5423
by: Szabolcs | last post by:
Is the following legal? void fun(int N) { int arr; } gcc and Digital Mars accept it, but msvc complains that it wants a constant expression.
22
3622
by: Tomás Ó hÉilidhe | last post by:
I've been developing a C89 microcontroller application for a while now and I've been testing its compilation using gcc. I've gotten zero errors and zero warnings with gcc, but now that I've moved over to the micrcontroller compiler I'm getting all sorts of errors. One thing I'd like to clarify is the need (in C89) for a compile- time constant in the initialiser of a variable. The compiler rejects the following source file: /* Start...
7
4271
by: Hendrik Schober | last post by:
Hi, this #include <string> class test { typedef std::string::size_type size_type; static const size_type x = std::string::npos; }; doesn't compile using either VC9 ("expected constant expression") or Comeau Online ("constant value is not known"). If I replace
56
6781
by: Adem | last post by:
C/C++ language proposal: Change the 'case expression' from "integral constant-expression" to "integral expression" The C++ Standard (ISO/IEC 14882, Second edition, 2003-10-15) says under 6.4.2(2) : case constant-expression : I propose that the case expression of the switch statement be changed from "integral constant-expression" to "integral expression".
0
9544
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
10259
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...
1
10238
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7570
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
6809
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
5467
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...
1
4145
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.