I've got this code:
#include <iostream>
int tabela[1];
tabela[0] = 1;
int main(){
std::cout << tabela[0];
std::cin.get();
return 0;
}
and it doesn't want to work. My compiler says " "tabela" doesn't name a type".
However if I do this:
#include <iostream>
int tabela[1];
int main(){
tabela[0] = 1;
std::cout << tabela[0];
std::cin.get();
return 0;
}
It works. Can sb explain me why? Thanks in advance.
At the outermost level, a C++ file is a sequence of declarations. tabela[0] = 1; is not a declaration - it's a statement (in particular an expression-statement). A function body, however, is a sequence of statements, so it's fine to put this line inside the body of main (or any other function).
Some statements are declarations (called declaration-statements), but in general they're not.
for it to be valid C++, you can only initialize variables in global, you can't assign them there.
edit: comments beat me to it. props
Related
#include <iostream>
using namespace std;
int x=15;
int main()
{
int x=10;
{
int x = 5;
cout<<::x; // should print 10;
}
return 0;
}
Is there any way to print x=10 without changing variable names, variable values and position of cout?
I assume this is an academic question (puzzle) because nobody should write code like that. In the same spirit, here's a way to make it print 10 instead of 15 without changing variable names, variable values and the position of cout:
#include <iostream>
using namespace std;
int x=15;
int main()
{
int x=10;
{
int x = 5;
#define x x-5
cout<<::x; // should print 10;
}
return 0;
}
Normally you should parenthesize such expressions in macros, like (x-5). In this case, that would be counterproductive :)
No you can't
An inner block, because it is a different block, can re-utilize a name existing in an outer scope to refer to a different entity; in this case, the name will refer to a different entity only within the inner block, hiding the entity it names outside.
Further information here: http://www.cplusplus.com/doc/tutorial/namespaces/
You cannot access x=10 in the inner block where you defined x=5. It can only see x=5 as x=10 is hidden at that point.
Ref: 3.3.7/1
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2).
If you don't mind some horrible undefined behaviour, we could make assumptions about where local variables are stored on the stack. This works on my machineā¢ using g++ without any additional flags (although even -O1 breaks it):
#include <iostream>
using namespace std;
int x=15;
int main()
{
int x=10;
{
int x = 5;
cout<<*((&x) + 1); // should print 10;
}
return 0;
}
This is based on the assumption that local variables are placed on the call stack (or some other place) consecutively in main memory, in reverse order of declaration. It breaks in many cases, such as having a different order, having x=10 be placed in a register, or x=10 being optimized away entirely because it's unused.
#include <iostream>
using namespace std;
int x = 15;
int main()
{
int x = 10;
{
int x = 5;
}
cout << x; // should print 10;
return 0;
}
you should probably put cout<< to outside
I am trying to learn C++ from the book Accelerated C++. At the end of Chapter 1 there is an exercise that tripped me. Essentially, I am wondering why the following code compiles and runs perfectly:
#include <iostream>
#include <string>
int main() {
{
const std::string s = "a string";
std::cout << s << std::endl;
{
std::cout << s << std::endl;
const std::string s = "another string";
std::cout << s << std::endl;
};
}
return 0;
}
It seems to me that I am doubly declaring the string s, and from my understanding this is illegal. Could you help me understand this better? Thanks. The output this produces is:
a string
a string
another string
In C++, you are allowed to redeclare a variable in a nested scope. Within that scope, the redeclared variable takes precedence.
See [basic.scope.hiding] for a standard reference:
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived
class
These are two seperate variable because they are declared in a different scope. The scope of a variable is the 'area' of code in which it's visible.
The outer s is overwritten with s in inner body.
New user, new to programming, x seconds of search didn't find me an answer.
Whole code (incomplete - and an online quiz for basic stuff):
#include "stdafx.h"
#include <iostream>
#include "constant.h"
double towerheight()
{
std::cout << "Input tower height" << std::endl;
double height;
std::cin >> height;
return height;
}
double ballheight(double towerheight)
{
//valid stuff goes here in program, but not applicable to question
}
int main()
{
double towerheight;
towerheight = towerheight(); //Error occurs here
ballheight(towerheight);
return 0;
}
3 lines from bottom ignoring whitespace and closing bracket is where the error occurs. (term does not evaluate to a function taking 0 arguments.)
I'm sort of lost at the research end of this and could use some human help.
Apologies for potentially poor formatting. Please advise, I may not know certain terms responsible for the error, and my goal is to understand what's going on.
EDIT:
Solution for me was changing the name of the double variable above the error. Why did this become an issue?
In main, the variable named towerheight shadows the function towerheight. Hence,
towerheight = towerheight();
is not valid. It is analogous to calling a function on a variable.
double towerheight;
double dummy;
towerheight = dummy();
That's why it is not correct.
Solution 1
You can use:
double towerheight;
towerheight = ::towerheight();
Using ::towerheight works since it refers to the name in the enclosing namespace and not the locally defined variable of the same name.
Solution 2
Use different names.
You can avoid some of the confusion by using two different names.
double t_height = towerheight();
The name of the variable is the same name of the function you are calling. You can change eighter the name of the variable or the name of the function. Usually when you are using C++ and declaring variables is a good practice to initialize the value of the double to something like 0.0.
And you are using 2 lines: 1 for declare the variable and another to give it the value when you can perfectly do this in one line. Better code uses less lines always keep it in mind.
This was my approach:
#include "stdafx.h"
#include <iostream>
#include "constant.h" //comented
double Gettowerheight()
{
std::cout << "Input tower height" << std::endl;
double height;
std::cin >> height;
return height;
}
double ballheight(double towerheight)
{
return 0.0;
//valid stuff goes here in program, but not applicable to question
}
int main()
{
double towerheight = Gettowerheight();
ballheight(towerheight);
system("pause");
return 0;
}
I put a return in the ballheight to compile the code as well as comment the 3rd include "constant.h"
Tested on Visual Studio 2013
I read code in buf0buf.cc of mysql's innodb buffer source code here:
link from git hub
And I got this:
&buf_pool->watch[0]
What is the value of the statement? address? or another value?
What does the code mean?(grammar meaning)
Due to operator precedence, this expression is parsed like:
&( (buf_pool->watch)[0] )
In English, the value is the address of the first element of the watch member container in buf_pool.
You can find out.
First of all, let's take the buf_bool variable and look for its declaration. As you can see a few lines above, it's a function parameter:
const buf_pool_t* buf_pool
This means we have to find the definition of the buf_pool_t type. With a mere full-text search, the type definition is not revealed. However, googling for "mysql buf_pool_t" gets us to http://www.iskm.org/mysql56/structbuf__pool__t.html, which in turn tells us that the type is defined in a file called buf0buf.h. That one's also included in the source file you've linked to:
#include "buf0buf.h"
It does indeed contain the definition we are looking for, and that definition includes a member called watch:
struct buf_pool_t{
(...)
buf_page_t* watch;
(...)
};
watch is a pointer to buf_page_t.
So if we go back to the statement in your question:
&buf_pool->watch[0]
watch is interpreted as a pointer to the first element of a buf_page_t array, watch[0] is the first element itself, and the address-of operator yields a pointer to that first element.
So the whole statement reads as:
a pointer to the first element of a buf_page_t array.
Curiously, &buf_pool->watch[0] is equal to buf_pool->watch. Here is a simple (C++11) toy program to verify all of this:
#include <iostream>
#include <typeinfo>
using buf_page_t = int;
struct buf_pool_t {
buf_page_t* watch;
};
int main()
{
const buf_pool_t example = { new buf_page_t[1] };
const buf_pool_t* buf_pool = &example;
std::cout << typeid(&buf_pool->watch[0]).name() << "\n";
std::cout << typeid(buf_pool->watch).name() << "\n";
std::cout << (&buf_pool->watch[0] == buf_pool->watch) << "\n"; // prints 1
}
&buf_pool->watch[0] is the the address of the member 0 of watch contained in the struct buf_bool. Which is watch itself.
It is parsed like that because the whole buf_pool->watch[0] gets under the & (address of) sign.
You can check with this snippet:
#include <iostream>
#include <stdio.h>
using namespace std;
struct hello_t
{
int before;
int array[5];
};
int main() {
// your code goes here
struct hello_t hello;
hello.array[0] = 100;
struct hello_t* ptr_hello;
ptr_hello = &hello;
printf("ptr_hello = %X\n", ptr_hello);
printf("&ptr_hello = %X\n", &ptr_hello);
printf("&ptr_hello->before = %X\n", &ptr_hello->before);
printf("&ptr_hello->array[0] = %X\n", &ptr_hello->array[0]);
printf("");
return 0;
}
https://ideone.com/fwDnoz
I am a java programmer trying to teach myself c++. Please cut me a little slack if I ask simple questions at first.
I would like to understand how the structure dereference operator works. Specifically, can anyone tell me what the following line of code does in explicit terms?
if (elements[i]->test(arga, argb)) {}
test(arga,argb) is a Boolean function in the same class, and elements is a vector of instances of the element class. Here is the code that immediately surrounds the line above, about which I am interested:
for (unsigned i = 0; i < elements.size(); ++i) {
T arga = INFINITY, argb = INFINITY;
//using namespace std;
//std::cout >> elements[i] >> std::endl;
//std::cout >> test(arga, argb) >> std::endl;
if (elements[i]->test(arga, argb)) {
//some code
}
}
It seems that the if line is testing to see whether or not the boolean returned by test(arga,argb) is part of the given instance of the elements class. But when I try to expose the underlying values of elements[i] or test(arga,argb) with the cout lines above, the compiler throws errors until I comment those lines out. In java, I would be able to fiddle around with this until I found values of each that correspond with each other, and then I would understand the line of code. But I do not know how to figure out what this line of code does in C++. Can anyone give me a clear explanation, preferably supported by a link or two to some references online?
elements[i]->test (arga, argb)
If we break down the statement, reading from left-to-right, we will end up with the below:
access the ith element in an array (or array-like) entity named elements
the element accessed (elements[i]) is a pointer to an object
call the member-function named test on elements[i] and pass it two arguments; arga and argb
if we disregard the fact that you wrote std::cout >> instead of std::cout << (the latter is the correct form), we end up with two reasons for your described errors:
your compiler complains about std::cout << element[i] because no suitable overload is found to handle an entity of the type of element[i] and an std::ostream& (which is the underlying type of std::cout).
your compiler complains about std::cout << test (arga, argb) because there is no function in scope named test that takes two arguments corresponding to arga, argv. test, in your snippet, is a member-function that belongs to an entity, it's not callable by its own.
Welcome to C++.
First, the syntax for output is:
cout<<
instead of
cout>>
You are right in guessing that test is a function that returns boolean.Here elements[i] is a pointer pointing to a struct element which has this test function.
To learn C++, you can use these articles that I wrote.Good luck!
Since numerous respondents told me that I need to provide the code before they can answer, I looked deeper in the code, and re-wrote something which tells me that the line:
if (elements[i]->test(arga, argb)) {}
is a test to see whether or not the boolean member function of elements[i] is true.
The c++ program that I wrote to identify the meaning of -> in this context is:
#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
template<typename T>
class Bone
{
public:
std::string myName;
int mySize;
Bone(const std::string &name, const int &size) : myName(name), mySize(size)
{}
bool isBigger(const int &testSize) const
{
if (testSize > mySize) return false;
else return true;
}
};
int main(int argc, char **argv)
{
std::vector<Bone<float> *> bones;
// name, location, size
bones.push_back(new Bone<float>("femur", 10));
bones.push_back(new Bone<float>("ulna", 4));
bones.push_back(new Bone<float>("maxilla", 3));
int testSize = 6;
// test each bone to see if it is bigger than testSize
for (unsigned i = 0; i < bones.size(); ++i) {
if (bones[i]->isBigger(testSize)) {
std::cout << bones[i]->myName; std::cout << " is bigger than testSize! " << std::endl;
}
}
while (!bones.empty()) {
Bone<float> *thisBone = bones.back();
bones.pop_back();
delete thisBone;
}
return 0;
}
Thank you to everyone who led me to figure this out.