473,811 Members | 3,356 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
15 2915
On Apr 21, 11:38 pm, "kar1...@gmail. com" <kar1...@gmail. comwrote:
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).
The PowerPC has a single instruction that performs that operation a =
b << c; if a, b and c are all in registers. There is _no_ single
instruction to calculate a = 1 << c: Two instructions are needed, one
to load the constant 1 into a register, and one to shift. Now if you
have an operation that calculates 1 << n in the critical path of a
very short loop with gazillions of iterations then this can make a
significant difference. This happened to me on a compiler that was
actually quite good at optimisations, except that it didn't recognise
that a constant can actually be a loop-invariant that should be
removed from a loop!

Similar things can happen with floating-point constants used in a
loop; a compiler should hold them in a register but often doesn't
whereas complex operations could be removed as loop-invariants from a
loop, with the result being kept in a register.

Apr 22 '07 #11
Ian Collins <ian-n...@hotmail.co mwrote:
Jack Klein wrote:
Despite what others have said, the C language standard does not
require a compiler to evaluate constant expressions at compile time
Vacuously true.
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".
What "unless"?

The standard simply says (Epmhasis mine): "A constant expression _can_
be evaluated during _translation_ rather than runtime..." There is no
"must"
or "shall" precluding runtime evaluation of all constant expressions.

Expectations of QoI is the only guide. But when it comes to constant
expressions, expectations are pretty high these days. :-)

--
Peter

Apr 23 '07 #12
Peter Nilsson wrote:
Ian Collins <ian-n...@hotmail.co mwrote:
>>Jack Klein wrote:
>>>Despite what others have said, the C language standard does not
require a compiler to evaluate constant expressions at compile time

Vacuously true.
Vacuous?
>>>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".

What "unless"?

The standard simply says (Epmhasis mine): "A constant expression _can_
be evaluated during _translation_ rather than runtime..." There is no
"must"
or "shall" precluding runtime evaluation of all constant expressions.

Expectations of QoI is the only guide. But when it comes to constant
expressions, expectations are pretty high these days. :-)
I have never come across a compiler that does not do this, so naturally
I assumed it was standard behaviour.
--
Peter
Your sig is missing the space after the --

--
Ian Collins.
Apr 23 '07 #13
Ian Collins <ian-n...@hotmail.co mwrote:
Peter Nilsson wrote:
Ian Collins <ian-n...@hotmail.co mwrote:
Jack Klein wrote:
Despite what others have said, the C language standard does not
require a compiler to evaluate constant expressions at compile time
Vacuously true.

Vacuous?
Yes, the notion of compile and link time are not mentioned. The word
"compiler"
only appears in a non-normative footnote of N1124. Obviously there is
an intuitive
mapping between the translation phases...

Preprocessing - TP1..4
Compilation - TP5..7
Linking - TP8

That said, there is often a degree of overlap on actual
implementations ,
particularly between compilation and preprocessing, especially with
pragma
extensions.
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".
What "unless"?

The standard simply says (Epmhasis mine): "A constant expression _can_
be evaluated during _translation_ rather than runtime..." There is no
"must" or "shall" precluding runtime evaluation of all constant expressions.

Expectations of QoI is the only guide. But when it comes to constant
expressions, expectations are pretty high these days. :-)

I have never come across a compiler that does not do this,
Nor are you likely to. Conditional preprocessing often involves
constant
expressions, so you're unlikely to find an implementation that can't
work
them out as it goes.
so naturally I assumed it was standard behaviour.
Whilst highly pragmatic and practical in nature, the language standard
is nonetheless an abstraction.
--
Peter

Your sig is missing the space after the --
As is...
--
Ian Collins.
Of course, I believe that you typed/inserted it.

Either google or IE managed to delete it. AFAIK, I'm not in a position
to
rectify this. If you're going to tell me how annoying it is for you,
then
realise that as a very reluctant google groups user I probably have to
do
things ten times more annoying than manually trimming signatures.

--
Peter

Apr 23 '07 #14
Peter Nilsson wrote:
Of course, I believe that you typed/inserted it.

Either google or IE managed to delete it. AFAIK, I'm not in a position
to
rectify this. If you're going to tell me how annoying it is for you,
then
realise that as a very reluctant google groups user I probably have to
do
things ten times more annoying than manually trimming signatures.
Like reading badly wrapped lines :)

--
Ian Collins.
Apr 23 '07 #15
On 22 Apr 2007 17:16:57 -0700, Peter Nilsson <ai***@acay.com .au>
wrote:
Ian Collins <ian-n...@hotmail.co mwrote:
Jack Klein wrote:
Despite what others have said, the C language standard does not
require a compiler to evaluate constant expressions at compile time

Vacuously true.
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".

What "unless"?

The standard simply says (Epmhasis mine): "A constant expression _can_
be evaluated during _translation_ rather than runtime..." There is no
"must"
or "shall" precluding runtime evaluation of all constant expressions.

Expectations of QoI is the only guide. But when it comes to constant
expressions, expectations are pretty high these days. :-)
True. But for some _integer_ constant expressions:

- the ICE specifying bitfield width in a struct must not be greater
than the 'normal' width (before C99, of [u]int) nor less than zero and
if zero must not be named; this is a constraint and so any violation
of it must be diagnosed. It's hard to do that without evaluating the
constant expression at compile time, unless you weasel out with a
blanket diagnostic like "this program may contain errors".

- the ICE specifying the value of an enumeratee must be in range of
int, as a constraint. This might not be too hard to defer, except that
the enumeratee can in turn be used in other ICEs which may need to be
evaluated.

- if the (integer) expression for array bound in a declarator is
constant it must be positive as a constraint; plus whether two array
types are compatible depends on whether their bounds are ICEs with the
same value, and compatibility is in some constraints.

- (ICEs for) case labels in a switch must be distinct, a constraint.

And as already noted, (integer) constant expressions in #if or #elif
must be evaluated at preprocessing time, at least in principle BEFORE
compile time, because
#if 0
#include "nonexistentfil e"
#endif
int main (void) { return 0; }
must succeed (or at least not fail because of that construct).

OTOH it may actually make sense to defer floating-point constant
expressions in cases of cross compilation where the target floating
point arithmetic is different from the host and not worth the trouble
of simulating or (God forbid) not documented well enough to simulate.

- formerly david.thompson1 || achar(64) || worldnet.att.ne t
May 21 '07 #16

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
2576
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
2839
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
10214
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
27445
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
5426
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
3625
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
4274
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
6786
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
9724
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
9604
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
10644
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
10379
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
7665
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
6882
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
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4336
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
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.