Author Topic: [GCC] can't make a calculation as part of variable setup  (Read 10899 times)

0 Members and 1 Guest are viewing this topic.

Offline snarkysparky

  • Frequent Contributor
  • **
  • Posts: 414
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #50 on: August 10, 2018, 12:52:26 pm »
for the compiler not knowing the type of a #define can you do this

#define someconst  (unsigned)42 

 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: [GCC] can't make a calculation as part of variable setup
« Reply #51 on: August 10, 2018, 01:11:42 pm »
don't abuse #define  :palm: :palm: :palm: :palm:
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: [GCC] can't make a calculation as part of variable setup
« Reply #52 on: August 10, 2018, 01:27:27 pm »
i have a hunting knife and it has this sawtooth like on the top that always bite me in the ass, that knife is not good and its not the safe practice, kitchen knife will be better because it has no sawtooth on the top, safe. knife is at fault not me, i'm perfect and clever, dont use define because i'm too lazy to declare type safe code and i can produce whatever bug in the program, define is at fault, define creates bugs not me. i'm perfect and better than Bjarne Stroustrup, i may as well design my own language and compiler :palm:, this is neverending story, people already went to the moon, we are here debating while polishing our fat ass, because thats good.
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: [GCC] can't make a calculation as part of variable setup
« Reply #53 on: August 10, 2018, 03:03:51 pm »
i have a hunting knife and it has this sawtooth like on the top that always bite me in the ass, that knife is not good and its not the safe practice, kitchen knife will be better because it has no sawtooth on the top, safe. knife is at fault not me, i'm perfect and clever, dont use define because i'm too lazy to declare type safe code and i can produce whatever bug in the program, define is at fault, define creates bugs not me. i'm perfect and better than Bjarne Stroustrup, i may as well design my own language and compiler :palm:, this is neverending story, people already went to the moon, we are here debating while polishing our fat ass, because thats good.

 :-DD :-DD :-DD :-DD :-DD
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #54 on: August 10, 2018, 03:13:09 pm »
Off-topic opinions on C++ follow...

C++ has the concept of constructors that (among other things) are used to initialise static variables. These are called before your main() function is run to handle cases like this. It is most likely also the source of undefined/random behaviors, as there is no clear order in which these get called, so most likely best avoided.

Static constructors are always called in order for a given file. But you're right, it's difficult to predict the initialization order of static variables that appear in different files. The problem isn't constructors though... Constructors are very useful! The issue is with using static class instances. The fewer static instances you have, the better.

You can (almost) have your cake and eat it too with placement new. You can allocate memory statically for an instance of a class, but delay calling the constructor until somewhere within main(). I use a template for that:

Code: [Select]
  /**
   * @brief returns a reference to a singleton instance
   * @tparam T the type of the singleton
   *
   * This template function uses placement new to statically allocate
   * memory for a single class instance, but delay its construction
   * until the function is called for the first time.
   *
   * Subsequent calls to the<T> return the same instance. The
   * constructor for T will only be called once.
   */
  template <class T>
  T &the() {
    alignas(T) static char memory[sizeof(T)];
    static T *             instance = nullptr;

    if (instance == nullptr) instance = new (memory) T;
    return *instance;
  }

and my main() usually looks like this:

Code: [Select]
int main() {
  the<Application>().run();
  return 0;
}

 

Offline snarkysparky

  • Frequent Contributor
  • **
  • Posts: 414
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #55 on: August 10, 2018, 03:24:55 pm »
Well might the gods of "best practice" actually shine their light on the situation,  just this once, and bestow their wisdom upon the mere mortals of the planet.

 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4028
  • Country: nz
Re: [GCC] can't make a calculation as part of variable setup
« Reply #56 on: August 10, 2018, 10:20:37 pm »
Well might the gods of "best practice" actually shine their light on the situation,  just this once, and bestow their wisdom upon the mere mortals of the planet.

It seems pretty simple to me. "Best practice" is to read and understand the manual for the tool you've chosen to use, and then decide for yourself how you want to use its capabilities and features.

Flailing around entering random input into your tool and expecting it to somehow intuit what you want is not best practice.

C is one of the simplest, most transparent, and least magical programming tools there is, second only to actual assembly language and maybe such simple orthogonal languages as FORTH or Scheme. The manual tells you precisely what you can do, what you can't do, and what is undefined.

With all of those simple languages you can build anything you want -- you're not restricted to what Brendan Eich or Guido van Rossum decided you should be able to do. The downside is that you *have* to build everything you want.
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 4199
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #57 on: August 10, 2018, 10:40:10 pm »
Quote
precompute the "constant" values at runtime.
Quote
switch to C++
Quote
enum {
    ADC_resolution = 13,
    ADC_factor = (1<<ADC_resolution) / 100,
    :
These are pretty extreme "solutions" for conforming to a "#defines are bad practice" suggestion, for a case where I think #define would work just fine.  (Especially the "enum" one - "#define is untyped, so instead we're going to use enum, which is a poorly defined type not-very-much like the actual data"???)



Quote
[8000000L and similar]
>> Those damn 16-bit C compilers used on small micros...
More like 8 bit compilers - that macro is from 8bit AVRs.
I wish they had never ported C to that damned PDP11!(actually, you don't need the "L" on numbers like 1000000; you're more likely to need "1L")
 

Offline ejeffrey

  • Super Contributor
  • ***
  • Posts: 3713
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #58 on: August 11, 2018, 03:26:18 am »
A classical discrepency between the GCC and G++ compilers. With godbolt.org, I noticed that this code (@brucehoult) will compile in GCC8.x and up, but not on older versions. On the other hand, it works in even the oldest G++ compilers.

However.. before GCC8.x flows downstream to IDE packages, you probably have to wait half a dozen years.
And I wouldn't recommended switching over a whole project to G++ because of this. That compiler is a bit stricter and your project may not compile (properly - under optimizations) elsewhere.

I would recommended replacing the "constants" with a macro in this case.

Well it isn't much a discrepancy between gcc and g++ as between C and C++.

C requires that all global variable initializers be expressions of literals.  A variable, even a "const" variable is not allowed in the initializer expression.  In principle, the language could be changed to allow "const" varaibles whose value is known, but this is not the case.  Note: you can have a "const" variable whose value is not known at compile time.  For instance, it could be "extern" (defined in a different source file), volatile (changeable by an external event), or forward declared with the value occurring later in the file.

This is one reason (of many) that despite the problems with #define macros it is most common to use #define for compile time constants, especially when you need multiple constants derived from each other.

C++ on the other hand lets you initialize global variables with almost anything you want including runtime computation.  This is handled by linker magic.  For instance, on ELF systems, every object file has a ".init" section.  Initializer code is placed in there and the linker makes sure that all code in .init sections gets called before main().

Note that this has "interesting" behavior too.  The order of initializers in different translation units is undefined, so initializing a variable from an "extern" variable is pretty much always wrong.  Furthermore, within a translation unit, the order of initialization depends on whether variables are const or not, *and* whether their initializer is a compile time constant.

 
The following users thanked this post: hans

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #59 on: August 11, 2018, 06:15:41 am »
These are pretty extreme "solutions" for conforming to a "#defines are bad practice" suggestion, for a case where I think #define would work just fine.
Another "solution" would be to quit worrying about having to compute everything at compile time. Composing a few bitmasks as the program runs isn't a big deal, and if it makes the code more readable/understandable, that's even better.

Besides, compilers are *really* smart these days, and even code that looks bulky may get collapsed into constants by a good optimizer.
 

Offline Nusa

  • Super Contributor
  • ***
  • Posts: 2416
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #60 on: August 11, 2018, 06:29:06 am »
Always remember that #defines are not constants, they're macro strings, and when you use them you're doing string replacement. Any evaluation happens at their point of use.

For example, some perfectly legal code:
Code: [Select]
#define A (2+
#define B 2+3)
#define C * 10
// Type your code here, or load an example.
int test() {
    return A B C;
/*    return (2+ 2+3) * 10;  // looks like this after macro replacement */
/*     return 70; // looks like this after compiler optimization */
}
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: [GCC] can't make a calculation as part of variable setup
« Reply #61 on: August 11, 2018, 08:27:54 am »
why people insist on using archaic cryptic U or L? |O that is meant for backward compatibility for languages that dont support more civilized syntax? when C already provides clearer and much more configurable type safe syntax such as:
Code: [Select]
#define my_data uint_32
#define my_const ((my_data)(3141))
otoh const <insert whatever data type> myVar will stay in memory forever and people or me and you can change the value with whatever untype unsafe syntax provided by the language. its best to think how compiler will do its job at compile time imho.

For example, some perfectly legal code:
Code: [Select]
#define A (2+
#define B 2+3)
#define C * 10
// Type your code here, or load an example.
int test() {
    return A B C;
/*    return (2+ 2+3) * 10;  // looks like this after macro replacement */
/*     return 70; // looks like this after compiler optimization */
}
its the people who code in such a way that embarked those people who complained C/C++ is cryptic garbage mess and not safe practice... i did it once (long time ago) because i need massive typing shortcut and save me alot of trouble when i tried to improve the code chunk which occured very many times, but this technique better we keep to ourself rather than advising people to do the same. its a "nasty language hack" that we can do with C/C++
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline Nusa

  • Super Contributor
  • ***
  • Posts: 2416
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #62 on: August 11, 2018, 10:12:36 am »
I wasn't trying to demonstrate good practice, I was trying to emphasize the nature of #defines. Thinking of them as constants means you're going to burn yourself again and again when you forget about operator precedence or forget necessary parentheses.

#define A 2+2
#define B (2+2)

int i = A;
int j = B;
int k = A * 10;
int l = B * 10;
// the values of i,j,k,l are 4,4,22,40. Do you understand why?
« Last Edit: August 11, 2018, 10:15:42 am by Nusa »
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: [GCC] can't make a calculation as part of variable setup
« Reply #63 on: August 11, 2018, 11:24:50 am »
C treats consts like variables, and doesn't always understand that they can never change

I don't agree with this. Constant is as constant does. Using #define won't solve the problem, and will make the code harder to debug and test later on.

yup, and it makes the code harder to debug!
 

Online IanB

  • Super Contributor
  • ***
  • Posts: 11859
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #64 on: August 11, 2018, 11:29:46 am »
C treats consts like variables, and doesn't always understand that they can never change

I don't agree with this. Constant is as constant does. Using #define won't solve the problem, and will make the code harder to debug and test later on.

yup, and it makes the code harder to debug!

But I have learned that the C and the C++ standards are a little different in this regard, and it is important to know whether you are using C or C++ when considering what behavior to expect.

(It is IMHO a little strange that the C and C++ languages are diverging. It would seem more sensible on the face of it for C to be a subset of C++.)
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: [GCC] can't make a calculation as part of variable setup
« Reply #65 on: August 11, 2018, 12:25:12 pm »
I can't use C++ for my stuff, for a lot of reasons.

It is IMHO a little strange that the C and C++ languages are diverging. It would seem more sensible on the face of it for C to be a subset of C++

The C language is defective in a lot of features, hence it's not weird that you see the C and C++ languages to diverge  :-//
 

Offline mikerj

  • Super Contributor
  • ***
  • Posts: 3238
  • Country: gb
Re: [GCC] can't make a calculation as part of variable setup
« Reply #66 on: August 11, 2018, 12:37:30 pm »
sounds like constants in C are still bollocks and the only true constant is a define.

So I need to split the operations up.

Sounds like you simply don't have a very good grasp of C yet.  If you define a 'const' value (const int my_const=5;), that value will exist in a memory location after the compiler has place it in the relevant memory section and the linker has allocated it an address.  Any code with visibility of this const value can read it, either via immediate addressing or via a pointer.  Since the preprocessor runs before the compiler (hence the name) you have been asking the preprocessor to use this value before it actually exists.

When you use #define with a literal value (e.g. #define MY_VALUE 5) the preprocessor creates a symbol that it can subsequently use to to replace any later instances of the symbol with that literal value.  This is not a constant value (though it can't change), it's a literal.  It won't have a unique memory address allocated for it, you can't access it via a pointer etc.
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: [GCC] can't make a calculation as part of variable setup
« Reply #67 on: August 11, 2018, 01:30:36 pm »
hence it's bad for debugging.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4028
  • Country: nz
Re: [GCC] can't make a calculation as part of variable setup
« Reply #68 on: August 11, 2018, 01:54:56 pm »
I can't use C++ for my stuff, for a lot of reasons.

What reasons?

If you can use C++ on an Arduino Uno with 2 KB of RAM (as you do) then there aren't many places you can't use it.

Using the C++ compiler doesn't force you to use any language features you don't want. You don't have to use exceptions. You don't have to use new and delete. You don't even have to use templates (though used skilfully they don't cause bloat) or classes (ditto). You can just treat C++ as a "better C".
 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: [GCC] can't make a calculation as part of variable setup
« Reply #69 on: August 11, 2018, 02:19:30 pm »
thats why they said... go hunting or camping with kitchen knife thats much safer. otoh looking from my eye, there is a serious semantics ambiguity going on between constant the number and constant the variable (memory allocated), or constant as in mathematics, and constant as in computing science. as for me, i prefer anything that is allocated in memory as "not constant" and anything "defined" or literal as "constant". imo, "const" keyword in C/C++ is just to let the compiler know that a programmer cant change it in legitimate way. but once you cast it to void and then back to another non const pointer, then it will be changeable like flint. btw i guess some people will rely on memory monitor/view while debugging instead of common sense or mental strength of whats that define means and how its semantically translated into a program.
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: [GCC] can't make a calculation as part of variable setup
« Reply #70 on: August 11, 2018, 02:30:24 pm »
What reasons?

Not technically reasons against C++, it's more a matter of convenience, i.e. I don't have enough money to buy a C++ compiler from Cosmic, while for my professional job, I am not often allowed to use C++ in avionics. We use Ada for everything needs abstraction and high-level design. Licenses for tools like Stood/C++ and Understand C++, as well as licenses for C++ debuggers, are usually 300-500% overpriced, hence as a freelancer, it's not so convenient for me to buy them, and I only have a regular pair of licenses for C's stuff. Anyway, in the past we did something in C++ (the customer paid for licenses, as their property), e.g. a couple of firmware for  Avionics Full-Duplex Switched Ethernet (aka AFDX), but the testing and the qualifying of C++ code is usually a bloodbath  :-//
« Last Edit: August 11, 2018, 04:51:15 pm by legacy »
 

Offline snarkysparky

  • Frequent Contributor
  • **
  • Posts: 414
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #71 on: August 11, 2018, 04:20:41 pm »
I see now.   5 expert in best practices would never even succeed in writing a hello world program if they must have consensus.

99.999%  of the software the world runs on has some suboptimal practice in the source.

Experts in best practice will argue about a knats @zz until the sun burns out.

Is it the norm in industry to have some smug sob criticize your code no matter what you do.

I suspect when they craft code the concept of "good enough"  runs in their head.  But when debating or reviewing others code the criticism  comes out.

I'm frustrated by these discussions which contain megabytes of criticism but microbytes of suggestions.

 |O
 
The following users thanked this post: Siwastaja

Offline legacy

  • Super Contributor
  • ***
  • !
  • Posts: 4415
  • Country: ch
Re: [GCC] can't make a calculation as part of variable setup
« Reply #72 on: August 11, 2018, 04:47:20 pm »
I'm frustrated by these discussions which contain megabytes of criticism but microbytes of suggestions.

hence, why don't you try to pass examinations like ACM and SIGACT in computer science (university), and then find a job in avionics, where you will be forced to master such concepts by practical contexts? :popcorn:

 

Online Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11622
  • Country: my
  • reassessing directives...
Re: [GCC] can't make a calculation as part of variable setup
« Reply #73 on: August 11, 2018, 06:44:34 pm »
not applicable in eevblog junkyard... and certainly dont ask Simon to do so...
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline snarkysparky

  • Frequent Contributor
  • **
  • Posts: 414
  • Country: us
Re: [GCC] can't make a calculation as part of variable setup
« Reply #74 on: August 11, 2018, 06:49:23 pm »
""hence, why don't you try to pass examinations like ACM and SIGACT in computer science (university), and then find a job in avionics, ""

who said I want to or need to.  A tiny percentage of the code written needs that level of care. If you answer for everybody to need that then your answer is incorrect.

which textbook will tell me what to do with #define and why casting a constant in there is bad.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf