the buffer and output sequence of cout and printf - printf

I know cout and printf have buffer today, and it is said that the buffer is some like a stack and get the output of cout and printf from right to left, then put them out(to the console or file)from top to bottem. Like this,
a = 1; b = 2; c = 3;
cout<<a<<b<<c<<endl;
buffer:|3|2|1|<- (take “<-” as a poniter)
output:|3|2|<- (output 1)
|3|<- (output 2)
|<- (output 3)
Then I write a code below,
#include <iostream>
using namespace std;
int c = 6;
int f()
{
c+=1;
return c;
}
int main()
{
int i = 0;
cout <<"i="<<i<<" i++="<<i++<<" i--="<<i--<<endl;
i = 0;
printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- );
cout<<f()<<" "<<f()<<" "<<f()<<endl;
c = 6;
printf("%d %d %d\n" , f() , f() ,f() );
system("pause");
return 0;
}
Under VS2005, the output is
i=0 i++=-1 i--=0
i=0 i++=-1 i--=0
9 8 7
9 8 7
Under g++( (GCC) 3.4.2 (mingw-special)), the output is,
i=0 i++=0 i--=1
i=0 i++=-1 i--=0
9 8 7
9 8 7
It seems that the buffer is like a stack. However, I read C++ Primer Plus today, and it is said that the cout work from left to right, every time return an object(cout), so "That’s the feature that lets you concatenate output by using insertion". But the from left to right way can not explain cout< output 9 8 7
Now I'm confused about how cout's buffer work, can somebody help me?

The output of:
printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- );
is unspecified. This is a common pitfall of C++: argument evaluation order is unspecified.
Not so with the cout case: it uses chained calls (sequence points), not arguments to a single function, so evaluation order is well defined from left to right.
Edit: David Thornley points out that the behavior of the above code is in fact undefined.

This is not a bug, nor is it anything to do with output buffering.
The order of execution of the i-- and i++ operations is not defined when they're invoked more than once as parameters to the same function call.
To elaborate (and possibly correct) Iraimbilanja's mention of "sequence points", the cout version is equivalent to:
(((cout << a) << b) << c)
Effectively, it's actually three separate function calls, each of whose parameters are evaluated in order, even though it's written like a single statement.
The << operator is really ostream& operator<<(ostream& os, int), so another way of writing this is:
operator<< ( operator<< ( operator<< ( cout, a ), b ), c )
Since for the outer call it's not (AFAIK) defined which order the two parameters are evaluated, it's perfectly possible for the right-hand "c" parameter (or in your case "i--") to happen before the left hand parameter is evaluated.

if possible try updating to gcc >= 4. i just ran this on 4.0.1 and it executes just dandy.

Related

How to find the complexity of the following loop

What would be the worst case running time of the following code where the input is 2 variables and loop exits when first variable becomes larger than the second one. My first guess was O(1) considering (x raised to 3) scales pretty quickly compared to (x raised to 2) but i don't know if it does close the gap quickly even when a is 1 and b is very very large integer.
i = 0;
cin >> a >> b;
while (a <= b)
{
i++;
a *= 3; b*= 2;
}
cout << i;
I think you are solving for the equation:
So solving for n, you get:
Assuming that b > a > 1.
Even for large differences, where a = 1.0001 and b = 10^1000, you get a small n = 41.8

Raku pop() order of execution

Isn't order of execution generally from left to right in Raku?
my #a = my #b = [9 , 3];
say (#a[1] - #a[0]) == (#b[1] R- #b[0]); # False {as expected}
say (#a.pop() - #a.pop()) == (#b.pop() R- #b.pop()); # True {Huh?!?}
This is what I get in Rakudo(tm) v2020.12 and 2021.07.
The first 2 lines make sense, but the third I can not fathom.
It is.
But you should realize that the minus infix operator is just a subroutine under the hood, taking 2 parameters that are evaluated left to right. So when you're saying:
$a - $b
you are in fact calling the infix:<-> sub:
infix:<->($a,$b);
The R meta-operator basically creates a wrap around the infix:<-> sub that reverses the arguments:
my &infix:<R->($a,$b) = &infix:<->.wrap: -> $a, $b { nextwith $b, $a }
So, if you do a:
$a R- $b
you are in fact doing a:
infix:<R->($a,$b)
which is then basically a:
infix:<->($b,$a)
Note that in the call to infix:<R-> in your example, $a become 3, and $b becomes 9 because the order of the arguments is processed left to right. This then calls infix:<->(3,9), producing the -6 value that you would also get without the R.
It may be a little counter-intuitive, but I consider this behaviour as correct. Although the documentation could probably use some additional explanation on this behaviour.
Let me emulate what I assumed was happening in line 3 of my code prefaced with #a is the same as #b is 9, 3 (big number then little number)
(#a.pop() - #a.pop()) == (#b.pop() R- #b.pop())
(3 - 9) == (3 R- 9)
( -6 ) == ( 6 )
False
...That was my expectation. But what raku seems to be doing is
(#a.pop() - #a.pop()) == (#b.pop() R- #b.pop())
#R meta-op swaps 1st `#b.pop()` with 2nd `#b.pop()`
(#a.pop() - #a.pop()) == (#b.pop() - #b.pop())
(3 - 9) == (3 - 9)
( -6 ) == ( -6 )
True
The R in R- swaps functions first, then calls the for values. Since they are the same function, the R in R- has no practical effect.
Side Note: In fuctional programming a 'pure' function will return the same value every time you call it with the same parameters. But pop is not 'pure'. Every call can produce different results. It needs to be used with care.
The R meta op not only reverses the operator, it will also reverse the order in which the operands will be evaluated.
sub term:<a> { say 'a'; '3' }
sub term:<b> { say 'b'; '9' }
say a ~ b;
a
b
ab
Note that a happened first.
If we use R, then b happens first instead.
say a R~ b;
b
a
ba
The problem is that in your code all of the pop calls are getting their data from the same source.
my #data = < a b a b >;
sub term:<l> { my $v = #data.shift; say "l=$v"; return $v }
sub term:<r> { my $v = #data.shift; say "r=$v"; return $v }
say l ~ r;
l=a
r=b
ab
say l R~ r;
r=a
l=b
ab
A way to get around that is to use the reduce meta operator with a list
[-](#a.pop, #a.pop) == [R-](#a.pop, #a.pop)
Or in some other way make sure the pop operations happen in the order you expect.
You could also just use the values directly from the array without using pop.
[-]( #a[0,1] ) == [R-]( #a[2,3] )
Let me emulate what happens by writing the logic one way for #a then manually reversing the operands for #b instead of using R:
my #a = my #b = [9 , 3];
sub apop { #a.pop }
sub bpop { #b.pop }
say apop - apop; # -6
say bpop - bpop; # -6 (operands *manually* reversed)
This not only appeals to my sense of intuition about what's going on, I'm thus far confused why you were confused and why Liz has said "It may be a little counter-intuitive" and you've said it is plain unintuitive!

Difference between 1 and 1'b1 in Verilog

What is the difference between just giving 1 and giving 1'b1 in verilog code?
The 1 is 32 bits wide, thus is the equivalent of 32'b00000000_00000000_00000000_00000001
The 1'b1 is one bit wide.
There are several places where you should be aware of the difference in length but the one most likely to catch you out is in concatenations. {}
reg [ 7:0] A;
reg [ 8:0] B;
assign A = 8'b10100101;
assign B = {1'b1,A}; // B is 9'b110100101
assign B = {1,A}; // B is 9'b110100101
assign B = {A,1'b1}; // B is 9'b101001011
assign B = {A,1}; // B is 9'b000000001 !!!!
So, what's the difference between, say,
logic [7:0] count;
...
count <= count + 1'b1;
and
logic [7:0] count;
...
count <= count + 1;
Not a lot. In the first case your simulator/synthesiser will do this:
i) expand the 1'b1 to 8'b1 (because count is 8 bits wide)
ii) do all the maths using 8 bits (because now everything is 8 bits wide).
In the second case your simulator/synthesiser will do this:
i) do all the maths using 32 bits (because 1 is 32 bits wide)
ii) truncate the 32-bit result to 8 bits wide (because count is 8 bits wide)
The behaviour will be the same. However, that is not always the case. This:
count <= (count * 8'd255) >> 8;
and this:
count <= (count * 255) >> 8;
will behave differently. In the first case, 8 bits will be used for the multiplication (the width of the 8 in the >> 8 is irrelevant) and so the multiplication will overflow; in the second case, 32 bits will be used for the multiplication and so everything will be fine.
1'b1 is an binary, unsigned, 1-bit wide integral value. In the original verilog specification, 1 had the same type as integer. It was signed, but its width was unspecified. A tool could choose the width base on its host implementation of the int type.
Since Verilog 2001 and SystemVerilog 2005, the width of integer and int was fixed at 32-bits. However, because of this original unspecified width, and the fact that so many people write 0 or 1 without realizing that it is now 32-bits wide, the standard does not allow you to use an unbased literal inside a concatenation. {A,1} is illegal.

Eigen: Replicate (broadcast) by rows

I'd like to replicate each row of a matrix M without any copy occurring (i.e. by creating a view):
0 1 0 1
2 3 -> 0 1
2 3
2 3
M.rowwise().replicate(n) is a shorcut for M.replicate(1,n) which seems kind of useless.
The following snippet does a copy, and cannot work if M is an expression.
Eigen::Index rowFactor = 2;
Eigen::MatrixXi M2 = Eigen::Map(M.data(), 1, M.size()).replicate(rowFactor, 1);
M2.resize(M.rows()*rowFactor, M.cols()) ;
In some situation, I may use the intermediate view Eigen::Map<Eigen::MatrixXi>(M.data(), 1, M.size()).replicate(rowFactor, 1) by reshaping the other operands, but that's not very satisfying.
Is there a proper way to achieve this broadcast view?
What you want is essentially a Kronecker product with a matrix of ones. You can use the (unsupported) KroneckerProduct module for that:
#include <iostream>
#include <unsupported/Eigen/KroneckerProduct>
int main() {
Eigen::Matrix2i M; M << 0, 1, 2, 3;
std::cout << Eigen::kroneckerProduct(M, Eigen::Vector2i::Ones()) << '\n';
}
Being 'unsupported' means that the API of the module is not guaranteed to be stable (though this module has not changed since its introduction, I think).

What does typedef enum syntax like '1 << 0' mean? [duplicate]

This question already has answers here:
What are bitwise shift (bit-shift) operators and how do they work?
(10 answers)
Closed 9 years ago.
I'm somewhat familiar with the typedef enum syntax of C and C++. I'm now programming in Objective-C and came across the syntax in the following example. I'm not sure if the syntax is Objective-C specific or not. But, my question is in the following code snippet, what does syntax like 1 << 0 mean?
typedef enum {
CMAttitudeReferenceFrameXArbitraryZVertical = 1 << 0,
CMAttitudeReferenceFrameXArbitraryCorrectedZVertical = 1 << 1,
CMAttitudeReferenceFrameXMagneticNorthZVertical = 1 << 2,
CMAttitudeReferenceFrameXTrueNorthZVertical = 1 << 3
} CMAttitudeReferenceFrame;
This is common to the C-family of languages, and works identically in C, C++, and Objective-C. Unlike Java, Pascal, and similar languages, a C enum is not limited to the values named for it; it actually is an integral type of a size that can represent all the named values, and one can set a variable of the enum type to an arithmetic expression in the enum members. Typically, one uses bit shifts to make the values powers of 2, and one uses bit-wise logical operations to combine values.
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0 // 1
} permission; // A miniature version of UNIX file-permission masks
Again, the bit-shift operations are all from C.
You can now write:
permission all = read | write | execute;
You could even include that line in the permission declaration itself:
typedef enum {
read = 1 << 2, // 4
write = 1 << 1, // 2
execute = 1 << 0, // 1
all = read | write | execute // 7
} permission; // Version 2
How do you turn execute on for a file?
filePermission |= execute;
Note that this is dangerous:
filePermission += execute;
This will change something with value all to 8, which makes no sense.
<< is called the left shift operator.
http://www.techotopia.com/index.php/Objective-C_Operators_and_Expressions#Bitwise_Left_Shift
Long story short 1 << 0 = 1, 1 << 1 = 2, 1 << 2 = 4 and 1 << 3 = 8.
It looks like the typedef is representing a bit field value. 1 << n is 1 shifted left n bits. So each enum item represents a different bit setting. That particular bit set or clear would indicate something being one of two states. 1 shifted left by zero bits is 1.
If a datum is declared:
CMAttitudeReferenceFrame foo;
Then you can check any one of four independent states using the enum values, and foo is no bigger than an int. For example:
if ( foo & CMAttitudeReferenceFrameXArbitraryCorrectedZVertical ) {
// Do something here if this state is set
}