|
It is written that you cannot take the address of a temporary value such as "(2 + 3)", does it apply for a const variable? |
No, the meaning of this slide is as follows: When you write in your code 5 or (a + b) it puts a temporary value. This value has a type (int in the first case, for example), but unlike a variable of the same type, you cannot use the & operator to take its address, as this temporary value's address has no meaning (and might not even exist after the compiler does its work). However, if you have a const int INVALID_MONTH = -1; you have a real variable in your code, and &INVALID_MONTH is just of type const int* .
|
In the slide about undefined behavior, what happens there? It makes no sense!! |
We're talking about the slide with the following code:
#include <stdio.h> #define N 7
int main() { int a[N] = {0}; int i; for (i=0; i < N; i++) { printf("%d\n", i); a[N-1-(i+1)] = a[i]; } return 0; }
And it is being compared to the code in which int i; appears before int a[N] = {0}; . First, note that this code accesses memory outside the array, this happens when i=6, in which case N-1-(i+1) is -1. This means that we are effectively writing a value outside the array and this is undefined. This means, that once we invoke such behavior, the program cannot be expected in any specific way. In practice, this is an example for how weird can undefined behavior get: In this case, writing 0 to a nearby memory address can result in rewriting the value of i to 0, thus, the loop will never end because every time i=6, 0 will be written to it. However, simply changing the declaration order, changes the location of variables in the memory and might cause a completely different behavior. The moral of the story: Once you invoke undefined behavior, everything can happen - including nothing, in which case it's hard to notice you did something wrong.
|
|