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 9078 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…
  • JWx
    JWx over 2 years ago

    Hello!

    int is at least 16bit (16bit when using 8bit Atmega or 32bit for Arm boards), byte is 8bit

    reference.arduino.cc/.../

    const informs compiler that variable is read-only (and can be optimized out to save memory in certain cases)

    define is a preprocessor macro that replaces name with value (or include/exclude parts of the program during compile time using #ifdef directive) - so this is directive for "find and replace" operation

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

    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(pin) == NOT_PRESSED.) Good solution for people who mistakenly think that pull-ups make the inputs inverted.

    In the past, I would always define things like pin functions as a const. But lately, I've been using #defines more. For any value that will fit into an 8-bit number, there is no performance difference between a #define macro or a const (of an 8-bit variable type.) For a const that fits into a register, most compilers won't bother treating it as a variable anyway.

    As usual, it is more important to be consistent in your code than get worked up over which is better.

    Regarding int versus byte, versus, whatever, except for byte and char, I have stopped using types like int. Instead, I use fixed-width integer types like uint8_t or uint32_t or int8_t. These are all part of stdint.h.

    Using fixed width removes the ambiguity of "How big is this variable on this processor with this compiler on this week of the year?"

    • Cancel
    • Vote Up +6 Vote Down
    • Sign in to reply
    • Cancel
  • Andrew J
    Andrew J over 2 years ago in reply to baldengineer

    Definitely the fixed width types, otherwise I find myself in the situation JWx mentions: at least .... and off we go to the races to find out what size is actually is.

    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
  • Jan Cumps
    Jan Cumps over 2 years ago
    • If I write proper C++ classes - and go through the effort to make good architectured designs - I use const and enumerators. In those cases, I try to use the new features that the language offers.

    class m25 {
    public:
      m25(spi_inst_t * spi, uint sclk, uint mosi, uint miso, uint ncs, uint nhold, uint nwrite) : 
        spi(spi), sclk(sclk), mosi(mosi), miso(miso), ncs(ncs), nhold(nhold), nwrite(nwrite) {}
      ~m25() {}
      void init();
      std::vector<uint8_t> rdid();
      std::vector<uint8_t> rdsr();
      void write(uint32_t address, std::vector<uint8_t> data);
      std::vector<uint8_t> read(uint32_t address, size_t length);
      void be();
    
      bool set_nhold(bool set);
      bool set_nwrite(bool set);
      void config_protect(bool srwd, bool bp2, bool bp1, bool bp0);
    
    private:
      enum commands : uint8_t { 
        WREN  = 0x06,
        RDID = 0x9F,
        RDSR = 0x05,
        WRSR = 0x01,
        READ = 0x03,
        PP   = 0x02,
        BE   = 0xC7 };
      spi_inst_t * spi;

    In the example, in some locations I used uint instead of uintxx_t, like baldengineer suggests. I am also a fan of the uintxx_t types. But this is a wrapper around the RP2400 SDK, and they use uint. 
    I try to adapt where I think it makes sense.

    • When writing C, and prototyping, I use defines. 
    • When I modify existing code, I usually stick to what the previous pundit used.
    • Cancel
    • Vote Up +2 Vote Down
    • Sign in to reply
    • Cancel
  • Andrew J
    Andrew J over 2 years ago
    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 down with a book/coding website and learn the basics of C programming.  It may be beneficial to skim C++ because you've probably come across a number of libraries written in this language - but that would be better on a "need to know basis".  I check your programming questions that you raise to see if I can help and will continue to do so, but I think you'd really benefit from investing some time in learning.  Understanding types and how they interact with each other (e.g. type casting) is critical; understanding modifiers such as const, static is also critical.  This doesn't mean you would then not copy-and-paste code but it would really help you understand what others are writing in their code and the bits that are genuinely relevant and/or how you might change it and integrate it better.  And I can promise you WILL become confident how to use them very quickly. Notwithstanding....

    int, byte, unsigned integer, .... are what are termed 'types' in a programming language.  They tell the compiler what type of value a variable will contain: e.g an integer cannot be assigned a value of 12.5 (actually, it can but it will be truncated to 12 but you get the point); similarly an unsigned integer variable cannot be assigned a value of -12 (again, it can but it will be some head-scratching value nothing related to the number 12 but calculated from a twos-compliment translation.)  In the cases where you do assign an invalid value you will get a compilation warning so you will know something strange has happened.  I can guarantee you get this: you know that you can assign a number to a number type and a character to a character type right?  You probably don't understand what the difference between int, signed integer, integer, unsigned integer, byte, float, double, long, etc etc... These are selected not just by what sort of number you can assign, e.g. an integer value such as 12 or a float value such as 12.5, but by the size of that number.  If you define a variable as a type of byte then it can only hold a value of 0 - 255 (8 bits) - if you assign it a value of, say, 257, it will just rollover and be set to 1 (0b100000001 - and only the last 8 bits are used) and you'll get a compiler warning.  The problem is that on different architectures, some of these types are different sizes: e.g. on a 16-bit processor int is likely to be 16-bit but on a 32-bit processor it is likely to be 32-bit (i.e. a much bigger number can be stored.)  There is no way around understanding this - you must check it for the processor you work with.  That's why James has mentioned STDINT library and the types defined there such as uint16_t which is guaranteed to be 16-bits irrespective.

    I think you're getting the idea that there is no substitute for learning this and whilst it may seem complicated, it really isn't once you set to it Slight smile

    const is just short for constant by which you promise the compiler you won't change the value post compilation, e.g.

    const String grassColour = "Green";
    ...
    grassColour = "Blue";
    ...

    The compiler would throw a wobbly seeing this and refuse point blank to compile.  There are other benefits which new programmers may not pick up on:

    const String grassColour = "Green";
    ....
    if (grassColour == "Green") {
      doSomeStuffHere();
    } else {
      doSomeCrazyOnDrugsStuffHereInstead();
    }
    ...

    The compiler would almost certainly optimise this code to:

    const String grassColour = "Green";
    ....
    doSomeStuffHere();
    ...

    Because the code in the else block can never be reached as grassColour is ALWAYS green.  It also does some other optimisation stuff like:

    const String grassColour = "Green";
    String leafColour = grassColour;
    ...

    Would get optimised to:

    const String grassColour = "Green";
    String leafColour = "Green";
    ...

    This has memory consumption benefits which is useful to know when developing for memory constrained systems.  Note there are syntactical variations where you define a constant but don't assign it a value at the same time; in this case the compiler will expect you to have initialised it before referring to it elsewhere in the code and then NOT to change it once you've done so.  There are probably edge cases where this is useful and worth understanding but in the majority of cases you would initialise the constant when you define it.

    #define is what is called a pre-processor macro (and in no way related to the way I have used "define" in the last sentence in the previous paragraph.)  Before compilation, a pass through the codebase is made dealing with the pre-processor statements.  In the case of #define, it is a substitution macro:

    #define grassColour "Green"
    ....
    String leafColour = grassColour;
    ....

    would become, after pre-processing and fed into compilation:

    String leafColour = "Green";
    ... 

    Every place in the source code where grassColour was used is replaced with the defined substitution.  Yes, you're right: that is JUST like using a const and is often used instead of creating const variables (an oxymoron if ever there was one) - in modern compilers that you would use there is no cost benefit to using either, and whilst purists might argue the nuances of one vs the other, for your purposes those arguments are irrelevant so pick a style and go with it.

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

    byte is used primarily in serial communications such as UART, RS485 (Better approach would be using uint8_t for serial communications).
    int is used to hold values from −32,768 to 32,767 which ideal for scenario where 2byte of signed data needs to be stored.
    const int is used as a reference for commonly known value. Such as const int boiling_point = 100 (better approach would be #define BOILING_POINT 100).

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

    I did a review of your material at the link for De-Bounce. I had read that #define is a text-based symbol substitution. I receive a tech tip in an email that suggested using it to #define MY_LED 13. This is what led to my confusion.

    int ledpin = 13;

    const byte ledpin = 13;

    and now

    #define led_pin 13

    What is a ressurectionist suppose to believe.

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

    I agree taking the time to learn is ideal. I have to balance that understanding with what I will retain. I will never be a programmer. I cobble together short snippets of code. Curiosity for the most part has me asking questions. 

    I appreciate you sharing your insight. Now if I can put it some where so I can recall it would be nice.

    Before I retired and when I was interested in furthering my career(s) I struggled with what to learn and what to retain. It seems I learned Pascal, VAX, Basic, Perl, python and xhtml but have retained little, especially in Perl. Coding Arduino's came when I retired. I did a full fledged course on Python during the pandemic and fall short of being able to write code from scratch.

    I have coded errors using wrong data types. Those I have managed to figure out. floats and int have caught me lately but I am getting better at identifying when they are needed.

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

    I like the suggestion but I have yet to find examples where it applies. That doesn't mean it is wrong, I have just seen it used to define pins that are not communication related. 

    Now that I have this knowledge I will look for it.

    • Cancel
    • Vote Up +1 Vote Down
    • Sign in to reply
    • Cancel
  • Jan Cumps
    Jan Cumps over 2 years ago in reply to colporteur
    colporteur said:
    I have coded errors using wrong data types.

    From experience, 3 good ways to learn coding really better:

    • join a software developer community. One where code is discussed. Discuss along. Do not ask for coding practices on an electronics forum Slight smile. (Except if you need an embedded specific advice)
    • read a book about professional coding, in the language you want to learn better (e.g.: Industrial Strength C++ by Mats Henricson an Erik Nyquist). 
    • read other people's code, love what they do well, and adapt it. 
    • 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