Tips of Embedded C
Tips of Embedded C
#include <string>
using namespace std;
int& f();
void func()
{
int n;
char buf[3];
n = 5; // n is an lvalue; 5 is an rvalue
buf[0] = 'a'; //buf[0] is an lvalue, 'a' is an rvalue
string s1 = "a", s2 = "b", s3 = "c"; // "a", "b", "c" are rvalues
s1 = // lvalue
s2 +s3; //s2 and s3 are lvalues that are implicitly converted to rvalues
s1 =
string("z"); // temporaries are rvalues
int * p = new int; // p is an lvalue; 'new int' is an rvalue
f() = 0; // a function call that returns a reference is an lvalue
s1.size(); // otherwise, a function call is an rvalue expression
}
An lvalue can appear in a context that requires an rvalue; in this case, the lvalue is
implicitly converted to an rvalue. An rvalue cannot be converted to an lvalue. Therefore,
it is possible to use every lvalue expression in the example as an rvalue, but not vice
versa.
How is a signed negative number stored in memory?
A:
In most intel architectures, signed negative numbers are stored in memory as two's
Complement.
0101 = +5
1011 = -5
int countbit2(uint n)
{ int bits = 0;
while (n != 0)
{
if (n & 1) bits++;
if (n & 2) bits++;
if (n & 4) bits++;
if (n & 8) bits++;
n >>= 4;
}
return bits;
}
How does, taking the address of local variable result in unoptimized code?
A: The most powerful optimization for compliler is register allocation. That is it operates the
variable from register, than memory. Generally local variables are allocated in registers.
However if we take the address of a local variable, compiler will not allocate the variable to
register.
Disadvantage: Macros and inline functions increased the size of executable code.
23. Which way of writing infinite loops is more efficient than others? there are 3ways.
While(1)
{
statements
}
or
do
{
statements
}
while(1);
or
for( ; ; )
Type qualifiers can be characterized by the restrictions they impose on access and
cacheing.
* const
No writes through this lvalue. In the absence of this qualifier, writes may occur
through this lvalue.
* volatile
No cacheing through this lvalue: each operation in the abstract semantics must be
performed (that is, no cacheing assumptions may be made, since the location is not
guaranteed to contain any previous value). In the absence of this qualifier, the contents of
the designated location may be assumed to be unchanged except for possible aliasing.
* restrict