Fundamental C - Variables |
Written by Harry Fairhead | |||||||
Monday, 08 April 2019 | |||||||
Page 3 of 3
In practice using stdint.h is a good idea, even if you are targeting a fixed machine, because it makes clear the exact size of the variables that are in use. Specifically, if you write: int myvar; then a programmer unfamiliar with the machine is left wondering what the size of the variable is, but if you use: int16_t myvar; then, even though this might map to int, it makes it clear that this is a 16-bit int. There are also macros that will create literals in the correct type: INTN_C(value) UINTN_C(value) create signed and unsigned literals with N bits. For example: INT16_C(255) creates a 16-bit signed constant for 255. There is more to say about macros in Chapter 14. Sections in the chapter but not in this extract:
lvalue and rvalueIt is clear that in an assignment there are left- and right-hand sides. Consider: a=2; In this case a is called an lvalue and 2 is called an rvalue. There is an important distinction between these two types of thing. The lvalue is the address of a modifiable entity. The rvalue is something that has a value, but it doesn’t have an address that can be used to access it. What this means is that: 2=a; is nonsense – you can’t assign to 2 as it doesn’t have an address that you can work with. However, notice that you can write: b=a; so lvalue doesn’t mean strictly on the left-hand side. Today we generally say that an lvalue is a locator value and it can be assigned to or retrieved and hence it can be used on both sides of an assignment. By contrast an rvalue really can only be used on the right of an assignment – it is, or can be reduced to, a value. As a more subtle point, you could argue that 2 is a literal and has to be stored somewhere and so modifying the literal is possible and so perhaps an rvalue can be assigned to. This is sometimes the case, but what about 2*b+a? This is an expression and while its constituents are stored somewhere its effective value is computed when needed. This is an rvalue for which assignment makes no sense and the simple literal 2 is a special case of an expression. The idea of an lvalue that has an “address” and an rvalue that might well not have an address is often helpful in understanding why some things can’t be used where an address is required. Summary
Fundamental C: Getting Closer To The MachineNow available as a paperback and ebook from Amazon.
Also see the companion volume: Applying C <ASIN:1871962609> <ASIN:1871962463> <ASIN:1871962617> <ASIN:1871962455>
Related ArticlesRemote C/C++ Development With NetBeans Getting Started With C/C++ On The Micro:bit To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
|||||||
Last Updated ( Monday, 29 April 2019 ) |