Defining Constants. Should I use CONST or

Sdílet
Vložit
  • čas přidán 19. 06. 2024
  • Patreon ➤ / jacobsorber
    Courses ➤ jacobsorber.thinkific.com
    Website ➤ www.jacobsorber.com
    ---
    Defining Constants. Should I use CONST or #DEFINE? // Just a quick video about constants. A lot of you have asked whether it's better to use preprocessor macros (#define) or const variables when defining your program constants. Both are acceptable, but they're not the same. This video breaks down some of the differences.
    ***
    Welcome! I post videos that help you learn to program and become a more confident software developer. I cover beginner-to-advanced systems topics ranging from network programming, threads, processes, operating systems, embedded systems and others. My goal is to help you get under-the-hood and better understand how computers work and how you can use them to become stronger students and more capable professional developers.
    About me: I'm a computer scientist, electrical engineer, researcher, and teacher. I specialize in embedded systems, mobile computing, sensor networks, and the Internet of Things. I teach systems and networking courses at Clemson University, where I also lead the PERSIST research lab.
    More about me and what I do:
    www.jacobsorber.com
    people.cs.clemson.edu/~jsorber/
    persist.cs.clemson.edu/
    To Support the Channel:
    + like, subscribe, spread the word
    + contribute via Patreon --- [ / jacobsorber ]
    Source code is also available to Patreon supporters. --- [jsorber-youtube-source.heroku...]

Komentáře • 151

  • @TheCocoaDaddy
    @TheCocoaDaddy Před 3 lety +110

    "Is that a constant?", "No, it's a const int". :) Great video! Thanks for posting!

    • @JacobSorber
      @JacobSorber  Před 3 lety +12

      😂 Beautiful. Thanks.

    • @pierreabbat6157
      @pierreabbat6157 Před 3 lety +8

      const int anople=537;
      istanbul=!anople;

    • @trefwoordpunk2225
      @trefwoordpunk2225 Před 2 lety

      It's not quite redundant acronym syndrome, but its close!

    • @StefanoTrevisani
      @StefanoTrevisani Před 2 lety

      @@JacobSorber you should make a new t-shirt: "contant != constint" or something along this line, would be quite funny!

  • @ramesh.programming
    @ramesh.programming Před 3 lety +83

    Yes, please make videos on function style macros...

    • @someperson9895
      @someperson9895 Před 2 lety

      THIS

    • @mason6300
      @mason6300 Před 2 lety

      please do...

    • @orisphera
      @orisphera Před 2 lety +1

      Also #ifdef and similar ones
      Fun fact: both the shortest (#if) and the longest (#elifndef) pp directives are in this family

  • @RajeshKulkarni26
    @RajeshKulkarni26 Před 2 lety +69

    In embedded systems where memory is precious , coders prefer macros to avoid loosing memory caused by using variables

    • @HansBezemer
      @HansBezemer Před 2 lety +4

      If you wanna go fast, the preprocessor is your friend ;-)

    • @sledgex9
      @sledgex9 Před 2 lety +19

      Modern compilers will optimize away the (static) const variable.

  • @anindyamitra5091
    @anindyamitra5091 Před 2 lety +1

    I just love the intro! 🔥🔥🔥
    Thank you for making the video, I was really curious about this thing.

  • @ronensuperexplainer
    @ronensuperexplainer Před rokem +4

    C++17 has "inline constexpr" variables that completely replace #define

  • @siddharthpandey3204
    @siddharthpandey3204 Před 3 lety +2

    Great content man, always waiting for your uploads!

  • @pumpkinhead002
    @pumpkinhead002 Před 2 lety +20

    You covered a lot of great points. Now, I know that embedded isn't always the focus of your videos; but in memory restricted systems, it is good to know the difference. I am working a bare metal system with very limited and sparse memory. we have dedicated ram space that is really small and dedicated flash space that is super large. Those are also divided up among the different sections of `.econst`, `.text`, etc. We use `const` to move data out of ram and into flash space, and use #define to move data out of `econst` and into `.text`. Thus managing how we fit our program into the space.

    • @grenadier4702
      @grenadier4702 Před 7 měsíci

      #define BUFFER_SIZE 32
      cosnt int BUFFER_SIZE = 32
      results in:
      mov eax, 32
      mov eax, 0xAF (the address of const int BUFFER_SIZE = 32)
      No difference, both commands take 24 bits, for example. In the latter case, you consume more memory and hurt perforamnce a tiny bit (if run your code without optimizations ofc)

    • @pumpkinhead002
      @pumpkinhead002 Před 6 měsíci

      @@grenadier4702 the latter case requires 24 bits in .text for the instruction and address, but Also requires space in .econst to hold the data "32" for which you address. So it takes more memory and actually consumes a "permanent" amount of it in the constant data section
      The former method does not use const section and instead relies totally on the program instructions to assign the 32. This gives us more data back in the const section as well as allows the 32 to be "unloaded" from the program during runtime.
      Granted it still exists in the flash somewhere, but in my particular example, the flash was not contiguous and our text section was significantly larger than the const sections as well as flash access being very slow.

    • @grenadier4702
      @grenadier4702 Před 6 měsíci

      @@pumpkinhead002 So there's no real poinmt in using const int instead of define in embedded systems? I see only downsides in doing that

  • @TheMR-777
    @TheMR-777 Před 3 lety +5

    Lemme answer some of the "Unknowing" about "Constant" attributes :)
    1. Where constant get saved?
    When we declare a Constant, it gets saved in the *Binary file* (executable file) and every time it's used in the program, it gets loaded from the Executable File your Compiler has generated. You can test this by viewing the Binary file in *HEX* Editor.
    2. Why/How the changed constant value doesn't get changed?
    - The answer actually depends on the *Type of the Memory* being used. Usually, when we change a variable, the Data is first loaded from the RAM and gets loaded in the particular Register. Then it gets modified according to our input and gets written on that RAM Location.
    - Now, in the case of constant, the Data from Binary (constant variable) gets loaded into the register, then updates as we did. But after that, the Binary file doesn't get written with updated data, as it's the Read-Only for the Execution Unit. That's the reason it doesn't get updated.
    - But if the particular compiler settings are enabled, Constants get saved on the RAM instead of the Binary file, and that's the reason sometimes you'll see them Changed.
    Hopefully, I have cleared the point. If there's any confusion, ask it in the reply.

  • @nashaut7635
    @nashaut7635 Před 3 lety +2

    Yet another great video :thumbsup: ! At #6:02 you might mention this is actually because changing a "const" is undefined behaviour. That's the reason why different compilers give different results. We do not want UB lurking in our code ;-) .

  • @LogicEu
    @LogicEu Před 3 lety +1

    Great stuff! I was just wondering about this matter. Thank you

    • @JacobSorber
      @JacobSorber  Před 3 lety

      You're welcome. Glad the timing was helpful.

  • @plumaligera8885
    @plumaligera8885 Před 3 lety

    The video about function style macros sounds great!

  • @a1nelson
    @a1nelson Před 3 lety +11

    A lot of good coverage of the topic here. I feel that some mention of the impact on the memory footprint would been a worthy addition to the video.

    • @elclippo4182
      @elclippo4182 Před 3 lety +1

      Yes, especially on embedded platforms with small memory and Harvard architecture (instead of von Neumann architecture).

    • @pablo_brianese
      @pablo_brianese Před 3 lety

      I recently was having doubts about this. I wondered whether declaring an int, even if const had a cost at runtime.

    • @makermatrix9815
      @makermatrix9815 Před 2 lety +1

      I just made this comment too. Would love to know the answer.

  • @osbaldotheVtenman
    @osbaldotheVtenman Před 3 lety +1

    Please, could you make #define style function macros. Great video. I always love how short and sweet yet immensely informative videos are

  • @1stblazer781
    @1stblazer781 Před 8 měsíci

    Helpful !!!! . keep it up Soldier !

  • @samaellovecraft
    @samaellovecraft Před 2 měsíci

    Thanks for the knowledge!

  • @warrenbuckley3267
    @warrenbuckley3267 Před 3 lety +1

    For the style of videos you make Jacob (short and to the point), a video on "struct hack" might be an idea.

  • @user-lt9oc8vf9y
    @user-lt9oc8vf9y Před 3 lety +16

    Another somewhat similar topic: what is your opinion of void* ? I really like them because they allow me to hide details and also act as generic types when combined with memcpy()

  • @EdwinFairchild
    @EdwinFairchild Před 3 lety +5

    A topic I've seen often is declaring something as "const volatile" or "volatile const" , usually used when using something like a status register in embedded and you don't want it to be modified because it's read only and at the same time it is volatile because it can change at anytime and should not be optimized out in any way. C is life man! Love your videos!!!!

    • @JacobSorber
      @JacobSorber  Před 3 lety +5

      Yeah, thanks for pointing that out. The first time I saw something that was both const and volatile, I was sure it was a joke.

    • @EdwinFairchild
      @EdwinFairchild Před 3 lety

      @@JacobSorber it does sound like an oxymoron

    • @maxaafbackname5562
      @maxaafbackname5562 Před rokem +2

      @@EdwinFairchild const meen "I" wil not modify it.
      volatile means that something else other than me will change it.
      Me versus something else.

  • @edgarbonet1
    @edgarbonet1 Před 2 lety +1

    Re the scope of a const: It is worth noting that, in C++, a const in file scope is only visible from the translation unit defining it. In other words, it has internal linkage (it is implicitly `static'). In plain C, however, a const in file scope is reachable from the whole program: it has external linkage.

  • @henrykkaufman1488
    @henrykkaufman1488 Před 2 lety +8

    You should use const for everything that you can rather than #define. #define is a preprocessor directive, it's much harder to debug since it's making preprocessor generate some code only later seen by compiler. In order for programmer to see what's actually generated by preprocessor, he has to read through intermediates. Also, preprocessor is very powerful and quite easy to use incorrectly (think C++ templates on steroids), so it should be used (it really should be used!) in a controlled way.

    • @1495978707
      @1495978707 Před rokem +1

      But in embedded systems where memory and speed are precious, it can be worth the cost of harder debugging. Especially since the programs are often simpler in the first place

  • @totaljustice1582
    @totaljustice1582 Před 3 lety +3

    Personally I use an enum. If the number is bigger than an int, then I’ll use a define, or if I won’t the value to be managed by build script, then I’ll use a define there as well. I use const if the var is local and it’s just 1 var. but if I want a local const for left and right for example, then I’d use an enum

  • @tordjarv3802
    @tordjarv3802 Před 3 lety +4

    Using #define might be your only option if you might compile your code with older c compilers. In my research group we have "work horse" machines all running older versions of Debian with gcc 6.x and you can't use const variables in expressions that should be constant, but on my private computer I have gcc 11.1.0 which has no problem with that.

  • @SoulSukkur
    @SoulSukkur Před 3 lety +9

    couple of comments from my experience:
    1) When I try to compile a program in C, I can't initialize an array when its dimensions are defined using a variable.
    2) When I place a constant in a header file, i can get dozens of linker errors. The solutions seems to be to declare it as an extern, and then define it in a .c
    So yeah, I use #define.

    • @ailijic
      @ailijic Před 3 lety

      For arrays, use an enum. For constants declare them with static. Don’t forget to use header guards.

    • @mohammedjawahri5726
      @mohammedjawahri5726 Před 3 lety

      I thought variable length arrays were legal as of some C version some time ago?

    • @rustycherkas8229
      @rustycherkas8229 Před 2 lety +1

      Header files are not a good place for application data. Their purpose is to "give the aroma" of datatypes and function prototypes to related "compilation units". So, yeah, a const int wouldn't be a good implementation if two compile units need to use a particular value.
      However, if your array's dimensions are dynamic (involving malloc), the header file can 'reserve' the token name (shared by all source files including that .H), and the linker will eventually make everyone happy.
      "Variable" usually means "can/will change value during execution. The compiler can't help you once it's done it's job...

    • @marcossidoruk8033
      @marcossidoruk8033 Před rokem +1

      @@rustycherkas8229 thats not what he meant. He meant you can't initialize an array if the dimensions are variables and it doesn't matter if those variables are const, the compilers just doesn't let you.

  • @raghavsrivastava2910
    @raghavsrivastava2910 Před 3 lety

    Great Video.

  • @JonnyRobbie
    @JonnyRobbie Před 3 lety +15

    I don't know. I still feel like you've "only" explained the difference, but haven't gotten to the meat of the question you teased in the title. Ok, now I now the difference, but WHEN should I use one and when the other?

    • @lycorisdev
      @lycorisdev Před 3 lety +3

      Always use #define, unless you need the constant to be a variable. He explained cases where a variable might be useful, so it's up to you whether you care about those cases or not

    • @kanony5188
      @kanony5188 Před 3 lety

      In primitive types like int there is not any difference (in most cases), but in types like struct -s you can't write with #define

    • @lycorisdev
      @lycorisdev Před 3 lety

      @@kanony5188 I don't know what you mean by "-s" structs, but of course a macro can't replace a struct

    • @simonfarre4907
      @simonfarre4907 Před 3 lety +2

      If you are using C++ *never* use define as some of these comments say - use constexpr.

    • @revealingfacts4all
      @revealingfacts4all Před 3 lety +9

      You always want to use a const over #define. In fact, you really should avoid # anything because it's not handeled by the compiler. Compiler will give you type checking that #define won't. This guy is wrong, it does not depend. Always prefer the compiler over the preprocessor. You can't debug code that is generated by preprocessor macros either. And this just scratches the surface. There are a host of other issues preprocessor macros introduce too he doesn't mention.
      I've been doing C/C++ for over 25 years mostly in embedded space and I hardly ever find a need to #define anything except for the #include guards.

  • @justcurious1940
    @justcurious1940 Před rokem

    Nice !!

  • @benjaminshinar9509
    @benjaminshinar9509 Před 3 lety +1

    there's also an older video that you made about debugging symbols, so if you use a variable, you can see the value in the debugger without any special modifications, but if you #define it, then you need some flags turned on.
    i prefer const, unless it's something that's controlled at the build level, in which case, that's the devops problem.

  • @ScioFantasia
    @ScioFantasia Před 3 lety

    Thanks for posting.
    @5:40 Note that this will not even compile in C++; pointers to const types must be const type *.

  • @agustinranieri
    @agustinranieri Před 3 lety

    I have an idea for a video: ¿how could I implement Promises or even Observables in C? Trying to understand how they work in behind

  • @preetishamballi6988
    @preetishamballi6988 Před 3 lety +1

    Further reading: Effective C++ by Scott Meyers, chapter 1, item 2.

  • @TheFootballPlaya
    @TheFootballPlaya Před 3 lety

    this is a great topic. one thing about c++ is it kind of forces the programmer to zoom into the actuality of how each statement will be processed at run-time versus compile-time. I like this content focused on macros, because it can be easily overlooked, and is pretty important

    • @IamusTheFox
      @IamusTheFox Před 3 lety +1

      macros don't happen at compile time, they happen before compile time.

    • @TheFootballPlaya
      @TheFootballPlaya Před 3 lety +1

      @@IamusTheFox is it because they are processed by preprocessor? or how are they handled? are they treated as textual?

    • @IamusTheFox
      @IamusTheFox Před 3 lety +1

      @@TheFootballPlaya yes, you're right. It's textual, at preprocessor time. It's why #includes work without effecting anything. Because it happens first.

    • @TheFootballPlaya
      @TheFootballPlaya Před 3 lety +1

      @@IamusTheFox ah i see. that's even more interesting now. thank you.

    • @IamusTheFox
      @IamusTheFox Před 3 lety +1

      @@TheFootballPlaya It's sad that all steps of compilation aren't thought well. Really glad to have helped!

  • @fabiovictorino350
    @fabiovictorino350 Před 3 lety

    I'm enjoy this canal

  • @SimGunther
    @SimGunther Před 3 lety

    I'd "define" numbers/straight up values, but use const for expressions that are evaluated at compile time.

  • @tomaszstanislawski457
    @tomaszstanislawski457 Před rokem +1

    There is an alternative way. Use untagged enumerations. `enum { ARRAY_LENGTH = 240 };`. This produces a true named integer constant that is properly scoped (not like a macro).

  • @MCLooyverse
    @MCLooyverse Před 3 lety

    One nice thing about macros is that you can have `#define CSI "\x1B["`, and then, somewhere in your code, have `CSI "J"`, which the preprocessor will turn in to `"\x1B[" "J"`, which is exactly the same as `"\x1B[J"`. I recently #defined a lot of ANSI escape code macros, so I am extra aware of this feature.

    • @FaranAiki
      @FaranAiki Před 2 lety +2

      Yup, this feature is yummy.

  • @simonmultiverse6349
    @simonmultiverse6349 Před 3 lety

    When I was working for a large company many years ago, I was programming in an ancient language, one of the ancestors of C. This large company was using an emulator to run this software, since the computer which originally could run it did not exist any more. The result was that the new, bigger computer ran the code more slowly than the original.
    I needed (for artistic reasons) to have variables which could be true or false, so I could check certain conditions, to see if a certain engineering calculation had converged to an answer. I defined two constants: NOWAY = 0 ; FERSURE = 1 ; I called these the California Booleans. There were snippets of code such as IF RESIDUALMAXITER THEN CONVERGED=NOWAY

  • @johnheaney3349
    @johnheaney3349 Před 2 lety +2

    Why no mention of enum? They are constants and essential for indexing because of the auto-increment feature.
    The other important distinction with #define is that preprocessor symbols can be used for conditional compiling. Can't do that with const variables or enums.
    #if NUM_ITEMS > 256
    //General purpose code goes here.
    #else
    //Optimization for singe byte values.
    #endif
    #ifndef MAX_BUFFER_SIZE
    #define MAX_BUFFER_SIZE 1024
    #endif
    On the other hand, macros are text substitution, so expressions are not necessarily optimized away and code size could change with optimization level.
    //Never even seen by the compiler unless it is used somewhere in code. Compiler sees expression on each usage.
    // Integer type depends on context. Never any storage allocation. Essentially, always a literal in code.
    #define MAX_BYTES (ITEM_SIZE * NUM_ITEMS)
    //Expression always resolved by compiler. Never an expression in code. Integer type dependent on compiler and sometimes the
    // size of the enum values. Essentially, a literal in code.
    enum {MAX_BYTES = ITEM_SIZE * NUM_ITEMS};
    //Expression always resolved by compiler. Never an expression in code. Explicit type. Compiler may optimize away storage.
    const int MAX_BYTES = ITEM_SIZE * NUM_ITEMS;

    • @johnheaney3349
      @johnheaney3349 Před 2 lety

      I forgot to add that you can take the address of a const variable, which of course forces storage allocation, regardless of optimization.
      Also, you can use sizeof().

  • @alexwang007
    @alexwang007 Před 3 lety +4

    Me as an engineer who can somewhat program:
    I came being forced to do java, and stayed willingly for C

  • @mfrdbigolin
    @mfrdbigolin Před 3 lety +9

    Nowadays I use mostly const, except for a constant string that needs to be concatenated with another string at compile-time, e.g.: puts ("Current program version: " VERSION);

    • @simonfarre4907
      @simonfarre4907 Před 3 lety +2

      And if you use C++ you should definitely use constexpr instead

  • @MahfuzurRahman-xl9pj
    @MahfuzurRahman-xl9pj Před rokem

    What is a translation unit? I am new to c programming and hear this term everywhere. Recently, I was studying about storage class (auto, register, static and extern) and came across this term. However, I am finding hard to understand the translation unit definition and the class specifiers.

  • @makermatrix9815
    @makermatrix9815 Před 2 lety

    Helpful. Is there a difference in terms of RAM usage? On something like an AVR where you've got 2500 bytes, saving every byte you can is sometimes critical.

    • @JacobSorber
      @JacobSorber  Před 2 lety +1

      There often is a difference, but that difference depends on what the compiler is doing and what optimizations are turned on. Often you're also trading data memory for code memory, which can sometimes be useful.

  • @michaelkotthaus7120
    @michaelkotthaus7120 Před 3 lety

    Like "BigCheese" already pointed out below, the enum has a certain advantage.
    Particularly, this does not work on file scope:
    const int ARRAY_LENGTH = 24;
    int array[ARRAY_LENGTH];
    But this:
    enum { ARRAY_LENGTH = 24 };
    int array[ARRAY_LENGTH];

    • @rustycherkas8229
      @rustycherkas8229 Před 2 lety

      As to your "no go" example, just swap where you define things:
      int array[ 24 ]; // limit is 2 dozen...
      const int ARRAY_LENGTH = sizeof(arrary)/sizeof(array[0]);
      This is much more flexible when adding or removing items from an initialised array:
      int array[] = { 1, 2, 3, 4, 5, };
      const int nElem= sizeof(array)/sizeof(array[0]);
      When you add 6, 7 and 8 to the array, the compiler will count the elements accurately.

  • @homelikebrick42
    @homelikebrick42 Před 3 lety +2

    I like to use a anonymous enum instead because it can be scoped

  • @jsjiang6120
    @jsjiang6120 Před rokem

    const int will cause larger code size since it needs a space to store the variable, which is not required for #define.

  • @junbird
    @junbird Před 3 lety +1

    I don't know about C++, but in C const is basically a misnomer. A const variable is still a variable and its value can change, meaning that there's no guarantee that its assigned value will stay constant. Some suggest thinking of a const variable as a read-only variable, rather than a constant attribute. Also, declaring an array with a const counts as declaring a VLA (Variable Length Array), an array which length is determined at runtime (since a const is initialized only at runtime), which use is highly discouraged.
    An alternative to #define is using an enum such as "enum { ARRAY_LENGTH = 240 }", which doesn't have the problems that using a const brings, while also being typed, (so it will throw much more readable errors if used improperly). Also, I might be saying something wrong here, but if you need to declare a constant which is the result of a computation, #define TWO 1 + 1 will just copy 1 + 1 wherever TWO is found during code preprocessing, so the program will have to resolve the expression each time it reaches a part of code which used the TWO symbol (even though I'd bet compiler optimizations would take care of that), while enum { TWO = 1 + 1 } would be processed just once at compile time (or so I think, please feel free to correct me).

    • @totaljustice1582
      @totaljustice1582 Před 3 lety +1

      You are correct about the 1+1. This is why you will see people then use (1+1) so that there’s no errors if the macro is used in more complicated equations, such as mult and div, the order may be important. But yeah the compiler would just make that value a 2 in that case. Also I completely agree about the enum as well! That’s the best way imo. One thing to note is that enums are ints, so they have the max size of an int. usually that’s okay, but if you have a very large number that’s bigger than an int, the compiler should(gcc will) warn about it, though maybe only will warn with -pedantic flag

  • @lorensims4846
    @lorensims4846 Před 2 lety

    I was always uncomfortable with the simple text replacement aspect of a #DEFINE, but I'm concerned the const int will add unneeded overhead within the executable. I guess it's just a few bytes so what's the diff? Who knows how the compiler might actually be using the result of that #DEFINE?
    I'll just have to do some test compiles and speed tests to figure out what I think about this.

    • @xCwieCHRISx
      @xCwieCHRISx Před 2 lety

      on normal computers this overhead of few bytes doesn't matter, but on micro controllers it can matter.

  • @mba2ceo
    @mba2ceo Před rokem

    How replace text by other text ? I want to replace cin

    • @maxaafbackname5562
      @maxaafbackname5562 Před 3 měsíci

      Text substitution does not work in strings.
      What you can do is:
      #define DAY "monday"
      std::cin

  • @StefanoTrevisani
    @StefanoTrevisani Před 2 lety

    This is one of the most important reasons I switched to C++: constexpr! Sure... You can use enums and pretend it's the same thing, but in the moment you need something other than an int, it still won't do.

  • @SystemSigma_
    @SystemSigma_ Před 10 měsíci

    In complex embedded projects with many submodules using #define for just constants is a mess. Pollutes everything and you end up with modules coupled by #define everywhere. Const and enums are your friend.

  • @rafaelcoelho5226
    @rafaelcoelho5226 Před 3 lety +1

    nice

  • @nunyobiznez875
    @nunyobiznez875 Před 3 lety +7

    Values in a #define actually do have a type, they're literals of type int, unless the value has U, L, D, F, etc. I often also hear the c++ community say macros are bad because they aren't type safe, which seems a bit absurd to me, because macros are no more or less type safe, than if the value is typed in by hand directly. It's only when macros are misused or abused, that there are problems with them, and as long as people remember they're a simple cut and paste operation, they work exactly as advertised and can be quite useful.

    • @mohammedjawahri5726
      @mohammedjawahri5726 Před 3 lety

      umm if you say this then you don't believe in type checking *in general*, typechecking is meant to prevent careless human error, u might as well say "hmm we never need types lol, every programmer should remember exactly what he put in what variable at what time, if it's corrupted it's his fault"
      I genuinely don't understand why anyone would ever want to opt for a macro instead of a constant with modern compilers, just look at the assembly generated by both on high optimization, even function style macros are obsolete with how much compilers inline (especially if u give hints that u want it inlined).
      edit: I think you're right about the point with typechecking constant literals. i misunderstood what you meant, but that's not really what people tend to mean when they talk about typechecking and defines, from what I've seen most people comment on function style macros where typechecking arguments would save hours of debugging

    • @johnheaney3349
      @johnheaney3349 Před 2 lety

      @@mohammedjawahri5726 A #define symbol can be tested when conditional compiling. Also, it is not seen by the compiler if not used in code.

  • @chennebicken372
    @chennebicken372 Před 2 lety

    What about constexpr in C++?

  • @KishoreG2396
    @KishoreG2396 Před 3 lety

    I use a constexpr in most cases

  • @AbinMathewAbraham
    @AbinMathewAbraham Před 3 lety

    Gotcha professor.... You typed a.out... so you are not using make files always...
    Just kidding... Love your videos ❤️

  • @harshavardhanbose
    @harshavardhanbose Před 29 dny

    I use templated static constexpr

  • @sledgex9
    @sledgex9 Před 2 lety

    Try to declare it as "static const int" instead of a global. Or, if in C++, put it inside an anonymous namespace.

  • @misana77
    @misana77 Před 3 lety +3

    1. Throwing away const and changing the value is undefined behavior that is am important concept both in C and C++ and had to be mentioned
    2. The code with discarding const is not going to be compiled in C++
    3. Please don't say that it is for C++. C++ has solved the problem with the constexpr keyword. Using macros for constants in C++ is a sign of not a C++ programmer or bad taught one

  • @wirosk2916
    @wirosk2916 Před 4 měsíci

    How about: #define ARRAY_LENGTH int(240)
    As I understand it the compiler would/could be aware if the type.
    And it should be optimized away in the asm.

  • @richardistvanthier5620
    @richardistvanthier5620 Před 3 lety +1

    use constexpr?

  • @kermitdafrog8
    @kermitdafrog8 Před 3 lety +1

    Where can we purchase a shirt like that?

    • @JacobSorber
      @JacobSorber  Před 3 lety +1

      jacob-sorbers-store.creator-spring.com/

  • @dynpallomah5918
    @dynpallomah5918 Před rokem +1

    For me, when
    1) a variable is global and is a guaranteed compile constant (numbers, bools that aren't assigned using variables etc), I'd use #define
    2) a variable is in scope, 99% of times I'd use const. That doesn't mean you can't #define, it's just that you have to #undef it at the end of scope and that's not elegant and is error-prone. As you can imagine const is way more common in my code
    3) I'm defining a function inside a function (tho it's not a good practise imo) and I'm not feeling to deal with lambdas and std::function I'd use #define to 'declare' the function (terrible practise but gets the job done)
    tl;dr use you fucking const, always

  • @pizzarda
    @pizzarda Před rokem

    genio

  • @milo20060
    @milo20060 Před rokem

    Also "mutable" will disable the const ^^

  • @gundam7463
    @gundam7463 Před 3 lety +1

    #define #define

  • @andrewbrownbill
    @andrewbrownbill Před 3 lety +1

    If it's c++, constexpr.

  • @XenoTravis
    @XenoTravis Před 3 lety +1

    'we don't really know'
    Until you look it up...

  • @glee21012
    @glee21012 Před 3 lety

    #define has scope in a namespace

  • @mes2009
    @mes2009 Před 2 měsíci

    Const better then define for type variable
    The all same you can not change

  • @nazarottto
    @nazarottto Před 3 lety

    Another alternative is enum.

  • @Christobanistan
    @Christobanistan Před 3 lety +1

    Does literally every developer use VS Code now??

  • @WistrelChianti
    @WistrelChianti Před 2 lety

    I feel I could upset people if I had a tshirt made with that pointer example on it...

  • @scottspitlerII
    @scottspitlerII Před 2 lety

    Hey Jacob! What do you think of the arguments that C is an old language not suited for modern systems programming and the folks at rust are trying to replace it? I personally disagree and think something not as drastic as Rust would be a better alternative. Thoughts?

  • @tk36_real
    @tk36_real Před 2 lety

    Maybe mention #undef

    • @questionmarc8
      @questionmarc8 Před měsícem +1

      It's #undef, not #undefine.

    • @tk36_real
      @tk36_real Před měsícem

      @@questionmarc8 yeah, obviously. silly mistake, thanks!

  • @IamusTheFox
    @IamusTheFox Před 3 lety

    If you care about performance why would you turn off an optimizer!? That makes no sense.
    Here's the problem with treating c++ and c as the same language. #define, esp function macros have their place in C, never in C++.
    define < const < constexpr < consteval.
    You can run can assign a value to a const with immediate invoking lambdas.

  • @yen7569
    @yen7569 Před 2 lety

    los mejores videos no estan en espanol

  • @arson5304
    @arson5304 Před 2 lety

    CONSTEXPR

  • @pierreabbat6157
    @pierreabbat6157 Před 3 lety

    An important use of #define is in the config.h file. You put a line like "test_big_endian(BIGENDIAN)" in CMakeLists.txt and "#cmakedefine BIGENDIAN" in config.h.in; this results in BIGENDIAN being defined or not in config.h, which you include in any source code that has to behave differently depending on endianness. The software version can be set similarly.

  • @KarabauPlay
    @KarabauPlay Před 10 měsíci

    for simple stuff, dont use #define. such as replacing a text with a number.
    also, in c++ instead of const int, which is global. use static constexpr int instead
    in fact, this video is mostly C convention, C++ has its own conventions regarding this topic.

  • @blank-vw2sb
    @blank-vw2sb Před 3 lety

    Whoa. prof, I really want to get in contact with you. How about creating a discord server?
    You aren't responding to me in instagram, prof!

    • @JacobSorber
      @JacobSorber  Před 3 lety

      Sorry. Not super responsive on IG. I'll think about the server idea. The best way to get project help is through Patreon.

    • @blank-vw2sb
      @blank-vw2sb Před 3 lety

      @@JacobSorber I'm not actually looking for project help. Just a computer geek to befriend. I know no body which loves programming as I do. But I can sense that geekiness in you, professor!

    • @blank-vw2sb
      @blank-vw2sb Před 3 lety

      @@JacobSorber please don't be sorry. if you make a discord server. Please let me know through your videos. Maybe a shout out?

    • @JacobSorber
      @JacobSorber  Před 3 lety

      @@blank-vw2sb Will do. Thanks.

    • @blank-vw2sb
      @blank-vw2sb Před 3 lety

      @@JacobSorber
      /*
      input [s] is supposed to be a output stream like cout. So pass one.
      */
      std::ostream& reply(std::ostream& s){
      return reply(s

  •  Před 2 lety

    What I hate about #define is that you can run into a #define that calls another #define that calls another... and you end up not knowing what it's doing.

  • @ladyViviaen
    @ladyViviaen Před 3 lety

    octalthorpe define > hash define / pound define

  • @Voltra_
    @Voltra_ Před 3 lety

    constexpr

  • @n-steam
    @n-steam Před 3 lety

    # = Hash
    £ = Pound

  • @markmanning2921
    @markmanning2921 Před 3 lety

    a typedef enum ftw

  • @williamwillis5729
    @williamwillis5729 Před 2 lety

    It's 'hash define' not 'pound define'. A pound sign is: '£'.

  • @user-sl6gn1ss8p
    @user-sl6gn1ss8p Před 3 lety

    "This is really s... something you shouldn't do"

  • @BlastinRope
    @BlastinRope Před 3 lety

    local_constants.h

  • @apocryphite_2
    @apocryphite_2 Před rokem

    I feel like you make mistakes on purpose to make us (the inexperienced) feel better.

    • @JacobSorber
      @JacobSorber  Před rokem

      If only that were true. I create plenty of genuine mistakes. But, if it makes you feel better, then I'm glad they served a valuable purpose.