Reputation: 31
I am currently learning C++ and saw this program when I was reading a book.
#include <stdio.h>
double counter = 50;
int main(){
for(int counter = 1; counter != 10; ++counter){
printf("%d\n",::counter/counter);
}
}
Now, I read up on the Scope Resolution Operator and I thought that this would print out the global variable counter divided by the local variable counter. However, the program prints out this:
2094374456
4195758
4195758
4195758
4195758
4195758
4195758
4195758
4195758
What are these numbers and what does the Scope Resolution Operator do in this case?
Disclaimer: I do not know C, but I have extensive experience in Java.
Upvotes: 0
Views: 95
Reputation: 75062
You used wrong format specifier. ::counter
will be the global counter
, whose type is double
, so the result fo division will have type double
and it should be printed via %f
format specifier or other specifier that calls for double such as %g
.
Passing data having wrong type will invoke undefined behavior in C, but I'm not sure about C++.
#include <stdio.h>
double counter = 50;
int main(){
for(int counter = 1; counter != 10; ++counter){
printf("%f\n",::counter/counter);
}
}
Upvotes: 1
Reputation: 119477
::counter
does indeed refer to the global variable counter
. The problem with this code is that the result of the division is of type double
since one of the arguments is, and a double
value is being passed to an ellipsis where int
is expected since the format specifier is %d
. This results in undefined behaviour. You need to change it to %f
.
Upvotes: 1