element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum When to use int, const int, const byte and Define
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • Replies 41 replies
  • Subscribers 384 subscribers
  • Views 9081 views
  • Users 0 members are here
  • programming
  • arduino_code
  • development
Related

When to use int, const int, const byte and Define

colporteur
colporteur over 2 years ago

I'm not a programmer. I am more of a ressurectionist. I find Arduino code pieces and join them together to make a program like Dr. Frankenstein joined body parts to create his monster. 

I see the statements listed in the question and wondered when do they apply. In collecting code parts from a number of programs, I can develop a program that has all four before the voids.  If I was to create a program from scratch I'm not confident I know what one to select for the variable type I am using.

Are there some best practices a novice could use in applying these to get the most benefit from their programming?

  • Sign in to reply
  • Cancel

Top Replies

  • baldengineer
    baldengineer over 2 years ago +6
    Personally, I used to only use #define for text-replacement. So, things like #define NOT_PRESSED 0x1, and #define PRESSED 0x0 for buttons. It makes if-statements more readable. For example, (if digitalRead…
  • Andrew J
    Andrew J over 2 years ago +4
    colporteur said: Are there some best practices a novice could use in applying these to get the most benefit from their programming? Please take this the right way: the best thing you could do is sit…
  • shabaz
    shabaz over 2 years ago in reply to beacon_dave +3
    Foo and bar are the worst! It never made sense. Reminded me of the stereotype of the nerd who deliberately uses the most complex sed/awk syntax he/she can think of. Especially since it doesn't take a genius…
  • colporteur
    colporteur over 2 years ago in reply to Jan Cumps

    I have visited that pool and discovered I don't really enjoy swimming there. I wasn't aware of the limitation between coding and electronics in the E14 Community. I assumed it was technology. Arduino technology such as coding was permissible.

    I will never get to the level of professional coding. Mine is an interest (they did it because) and not a profession (it is important that do that because). Great resource I will try and use it. I like the reference to style in the appendix. I seem to recall I had a similar reference style-guide for Python in Visual Studio. At least my code looked I knew what I was doing:)

    The last bullet point works if you have the knowledge to understand why they did what they did and not why they did something different. This whole thread was sparked from a tech tip I received in an email about using #define. 

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • beacon_dave
    beacon_dave over 2 years ago

    May or may not help but Microchip published a couple of short courses on the fundamentals of embedded C, which might help with filling in some of the gaps.

    https://mu.microchip.com/syntax-and-structure-of-c

    https://mu.microchip.com/advanced-c-programming

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • Andrew J
    Andrew J over 2 years ago in reply to colporteur

    int ledpin = 13; // The compiler will reserve 16-bits (assuming 16-bit processor) at an address in memory to store the number 13 0b0000000000001101.  that address will be used to retrieve the literal when used, every time, because the compiler has no knowledge if that value will change.

    const byte ledpin = 13; // the compiler (if it is half decent) will almost certainly substitute the use of variable ledpin with an 8-bit literal value 0b00001101.

    #define led_pin 13; // the pre-processor will text substitute, in source non-permanently, the word "led_pin" with the text "13" and then send the source to the compiler.  The compiler will then treat it as a literal integer (so like the const definition) but whether that would be as a 16-bit literal or an 8-bit literal would need to be researched because I don't actually know (it's an interesting thought actually and my first suspicion is that it would choose the most optimum bit size, 8 in this case!)

    Any of these work but a ressurectionist will always struggle because they look radically different.  However, this stuff is as basic to programming as understanding Ohms law in electronics.  I'm an (ex-)developer, albeit one who hasn't had a professional development role for over 20 years, who had zero knowledge of C when I picked up an Arduino, so I actually spent some time understanding how the language dealt with types, working out the differences between const and #define, what happens if types are mixed in an expression (e.g int aVar = 12 / 7.1; ) and so on.  These things are so fundamental that even a resurrectionist should take the time to understand it if they intend to spend any time with microprocessors, including Arduino, because copy-and-paste will very often introduce strange errors into existing code (as, I think, you have found out on many occasions.)  I say this in the nicest possible way and not to criticise at all - I honestly believe it will increase your enjoyment of working with Arduinos if you understand a little more than you currently do.  It really will be worth the effort and we can help you clarify points of understanding.  

    I still have a problem with C in that it would appear that many 'experienced' C programmers seem to go out of their way to write C code in as an obscure a manner as possible!  I also struggle with pointers despite reading umpteen articles about them and I have to revisit constantly.  

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • Andrew J
    Andrew J over 2 years ago in reply to Jan Cumps

    Jan, what do functions rdid() and rdsr() do?  Ditto set_nhold() and set_nwrite()?  I don't mean, the code, but what you would say in a function comment for them?  rdid() - is that reading an id for example?  What are the purposes of variables srwd, bp2?  

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
  • colporteur
    colporteur over 2 years ago in reply to beacon_dave

    The snow storm here is almost over. Maybe next time:)

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Cancel
  • phoenixcomm
    phoenixcomm over 2 years ago

    OMG  "colporteur "When to use int, const int, const byte and Define", I have been working with K&R and then ANSI C since the mid '70s.  Let me start at the top and work to the bottom;

    • int ::= any time you want any sort of number (whole only)
    • cont int        this is stupid lets me tell the compiler that I am not going to change its value; 
    • const byte   "
    • #define::=  This is a macro;  I use this to assign values for a named variable such as "#define FAIL -1;" or things that are not in the library like the value of pi. or a square "#define sqr(a)  ((a)*(a)",  

    NOTE: error messages and I have quite a few some of my boxes will have 50+ error messages. here is the best way to handle them. The key is to standardize them. so lets build a structure of error messages:

    typedef struct eMessages{
      int errorNumber;
      int equipment; 
      int formatType;     // this is info we send to the formatter
      char[200] error;    //message long
      char[20]  errorsh;  //short version
      } errorMessages;
      
      all error messages can now be unified
      
      void ErrorMessage(int errorNumber, int equipment, int formatType ){
      time_t current_raw_time = time(0); // System time:
       printf ( "%02d:%02d:%02d: #%10d -- #%u -- %s200 \n" errorMessages, int equipment, formatType);

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • Prasanth_R
    Prasanth_R over 2 years ago in reply to colporteur

    Ok, I got your confusion. I created a simple function that prints pin number specified in different data types using Compiler Explorer (godbolt.org)
    As you can see from the assembly language, compiler considers
    #define and const declaration as same and directly copy the absolute value to register.
    int as a 32bit value (double word).
    byte as 8bit value, which compiler copies to lower byte and set 0 to rest of the higher order bytes.

    Considering pin number won't change during compilation or run time and less amount of processing required pin definition can be made using const or #define types.

    image

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • beacon_dave
    beacon_dave over 2 years ago in reply to colporteur

    5 mins a day would soon get you through it. Time you are likely to get back starting from your next project.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • obones
    obones over 2 years ago

    When compiling, you have multiple steps, three of them being preprocessor, compiler and linker in that order

    The preprocessor takes your source files, modifies them "in memory" and passes the result to the compiler

    The compiler takes its input and generates machine code in the form of object files (.o)

    The linker takes all object files and creates the final application file (.exe under Windows, .bin for firmware...)

    #define NAME value tells the preprocessor to replace NAME by value wherever it sees it. It is just like copy/paste but done for you by the preprocessor, which means the compiler will never see the NAME item, only a repetition of value in lots of places

    const int and int only differ in semantics, the "const" specifier telling the compiler that it should not allow any code to change the value. As this is seen by the compiler, you can "take" the address of the constant by using the ampersand (&) operator, which might be required by some libraries and is even more convenient when dealing with structures because all you deal with is a pointer (32 bits on 32 bits architecture) and not the entire structure itself (that can range in the dozen of bytes)

    Finally, the linker can do some serious optimizations with constants when they have the same value by "merging" them together, meaning that 10 constants with the same value only occupy their size once in the final firmware. While this does not mean much under desktop OSes, it can be very important on embedded architectures.
    One other benefit of "const" is that on architectures like the ESP32, the value is not placed in RAM but in Program memory. As RAM is very limited (120k contiguous at most), it is of the utmost importance to place as little things as possible in there.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • Jan Cumps
    Jan Cumps over 2 years ago in reply to Andrew J

    > what do functions rdid() and rdsr() do?

    That's the name of a function you can do with flash.

    image

    > Ditto set_nhold() and set_nwrite()?

    set the IC's NHOLD and NWRITE pins

    image

    > What are the purposes of variables srwd, bp2?  

    image

    I did that deliberately - match the manufacturer's names.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
<>
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube