Works:
int GlobalVar = 5;
int * LPVar[] = {&GlobalVar};
Doesn't work:
int GlobalVar = 5;
int * LPVar[]; // int * LPVar[1] doesn't work too
LPVar[0] = &GlobalVar; // errors here
------ Build started: Project: pointers, Configuration: Release Win32 ------ Compiling... ilovpointers.cpp .\ilovpointers.cpp(9) : error C2466: cannot allocate an array of constant size 0
.\ilovpointers.cpp(9) : error C4430: missing type specifier - int
assumed. Note: C++ does not support default-int .\ilovpointers.cpp(9)
: error C2040: 'LPVar' : 'int []' differs in levels of indirection
from 'int *[1]' .\ilovpointers.cpp(9) : error C2440: 'initializing' :
cannot convert from 'int *' to 'int []'
There are no conversions to array types, although there are conversions to references or pointers to arrays Build log was saved at
"file://f:\Visual Studio
C++\Project1\pointers\pointers\Release\BuildLog.htm" pointers - 4
error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
EDIT:
I solved but got question.
#include <iostream>
#include <stdio.h>
using namespace std;
int GlobalVar = 5;
int * LPVar[1];
void main()
{
LPVar[0] = &GlobalVar;
printf("%i", *LPVar[0]);
cin.get();
}
LPVar is a global array so why it didn't work when I have put it just after definition?
Is the code at file scope?
The answer appears to be yes given the updated code fragment.
If so, you can't have random assignments like LPVar[0] = &GlobalVar; written at file scope. You can only have declarations (without initializers) or definitions (optionally with initializers) at file scope.
In your question, this works (as indeed it should), because there are two variable definitions with initializers.
int GlobalVar = 5;
int *LPVar[] = {&GlobalVar};
This code does not work (as indeed it shouldn't), because the third line is an assignment statement and not a declaration or definition:
int GlobalVar = 5;
int *LPVar[]; // Declaration, not definition
LPVar[0] = &GlobalVar; // Assignment is not allowed outside a function body
Variant:
int GlobalVar = 5;
int *LPVar[1]; // Definition without initializer
LPVar[0] = &GlobalVar; // Assignment is not allowed outside a function body
Related
UPDATE:
Thanks to everyone for the help to understand this!
I try to run this:
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
and i get the following errors:
1>------ Build started: Project: learnCpp, Configuration: Debug Win32 ------
1>learnCpp.cpp
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,2): error C2374: 'x': redefinition; multiple initialization
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(3): message : see declaration of 'x'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,7): error C2440: 'initializing': cannot convert from 'int' to 'int *'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,4): message : Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "learnCpp.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
however I don't get any errors if I assign the value to x inside the main function.
Like so:
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
How come?
In the file scope in C you may place only declarations. You may not execute statements in the file scope. The same is valid for C++ where you may place in a namespace only declarations.
Note: In C declarations are not statements while in C++ declarations are statements. Nevertheless except the declaration statement other statements may not be present in a namespace in C++. It is interesting also to note that in C there is a null statement but there is no an empty declaration. While in C++ there may be an empty declaration.
So this program
#include <iostream>
int* x = new int;
*x = 5;
int main()
{
}
is invalid.
These error messages of the compiler
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2374: 'x': redefinition; multiple initialization
message : see declaration of 'x'
mean that the compiler tries to interpret the assignment statement as a declaration.
But this program
#include <iostream>
int* x = new int;
int main()
{
*x = 5;
}
is correct. In this program the assignment statement is present in the outer block scope of the function main.
What you are trying to do is not possible in global scope.
If you need to do this way try to initialize as below :
// good practice
namespace
{
int* x = new int(5);
}
int main()
{
// You can later modify in function scope
*x = 10;
}
You cannot have statements other than declarations, outside of any scope (for simplicity consider a scope whatever is inside brackets). So, compiler is trying to interpret
*x = 5;
as a declaration, so as a pointer to a given type, but does not find the type pointed to, so generates an error.
I am trying create a typedef for a template that needs a pointer to member, from within a class. The best way to describe it is to show the minimal sample code:
template<typename T, int T::*MV>
struct Bar
{
const int &value(const T &t) const
{
return (t.*MV);
}
};
struct Foo
{
int baz;
typedef Bar<Foo, &Foo::baz> GetBaz; // Compiler error
};
typedef Bar<Foo, &Foo::baz> GetFooBaz; // Compiles just fine
int main(int argc, char* argv[])
{
Foo f = { 42 };
Foo::GetBaz b; // Fails to compile
GetFooBaz b2; // Fine
int val = b.value(f); // Fails to compile because of above
int val2 = b2.value(f); // Fine
}
I am not necessarily dead-set on getting access to a member pointer in this way, I would be fine just knowing the offset to the variable and having the Bar::value function perform trickery.
As a last resort, I suppose I could use a traits class since the would move the definition outside of the class, but I would prefer to be able to declare the typedef near the variable being used.
And, to answer the "why would you want to do that" question, this is all for an IoC container that closely represents the way MEF (C# works).
The specific compiler I am using is VC12, but it would be nice if VC11 supported it as well.
Thanks
EDIT:
Here are the error messages
1>------ Build started: Project: MemVarBug, Configuration: Debug Win32 ------
1> MemVarBug.cpp
1>memvarbug.cpp(20): error C2327: 'Foo::baz' : is not a type name, static, or enumerator
1>memvarbug.cpp(20): error C2065: 'baz' : undeclared identifier
1>memvarbug.cpp(20): error C2975: 'MV' : invalid template argument for 'Bar', expected compile-time constant expression
1> memvarbug.cpp(7) : see declaration of 'MV'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
you can do the following trick:
declare baz to be int[1];
array of size one, in this case calling baz will return the pointer and calling *baz will return the value.
AIBase* allai[2];
AIBase *z0AI = new AIA;
AIBase *z1AI = new AIB;
allai[0] = z0AI;//this this gives me an error
allai[1]= z1AI;
AIBase is the superclass and AIA and AIB inherits from the AIBase
what is wrong with the syntax ,i need some help in figuring this out
error 1:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2466: cannot allocate an array of constant size 0
error C2040: 'allai' : 'int []' differs in levels of indirection from 'AIBase *[2]'
Why must this code be in function scope? Cant this work in global scope?
In C++ (and C), executable code that is not a variable initialiser must appear inside a function. Executable code cannot appear at file scope (that is, outside any function).
So, just put your code inside a function:
int main(int, char *[])
{
AIBase* allai[2];
AIBase *z0AI = new AIA;
AIBase *z1AI = new AIB;
allai[0] = z0AI;
allai[1]= z1AI;
}
include "stdafx.h"
#include <iostream>
using namespace std;
class Foo{
public:
void func()
{
cout<<"Hello!!"<<endl;
}
};
void some_func(const Foo &f)
{
//f.func();
Foo &fr=const_cast<Foo&>(f);
fr.func();
}
int main()
{
some_func(Foo &f); //if const declared will add the no of errors from 2 to 3
return 0;
}
How to invoke the some_func(const Foo &f)...If i declare the const before Foo parameter in main it shows me error...
But if i'm using the code above i'm getting 2 errors..
output:
1>------ Build started: Project: const_cast, Configuration: Debug Win32 ------
1>Compiling...
1>const_cast.cpp
1>c:\documents and settings\beata\my documents\visual studio 2008\projects\const_cast\const_cast\const_cast.cpp(24) : error C2065: 'f' : undeclared identifier
1>c:\documents and settings\beata\my documents\visual studio 2008\projects\const_cast\const_cast\const_cast.cpp(24) : error C2275: 'Foo' : illegal use of this type as an expression
1> c:\documents and settings\beata\my documents\visual studio 2008\projects\const_cast\const_cast\const_cast.cpp(8) : see declaration of 'Foo'
1>Build log was saved at "file://c:\Documents and Settings\beata\My Documents\Visual Studio 2008\Projects\const_cast\const_cast\Debug\BuildLog.htm"
1>const_cast - 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Your problem is probably with main()
int main()
{
Foo f;
some_func(f);
return 0;
}
You need to declare f before you can use it.
int main()
{
Foo f;
some_func(f);
return 0;
}
some_func(Foo &f); looks something like a declaration and something like a function call. If you meant a function call you just pass an object of the appropriate type to the function. E.g.
Foo f;
some_func(f);
or if you want to pass an unnamed temporary (legal because the function takes a const reference):
some_func(Foo());
The problen you're seeing is that you haven't labled the func function call as const to indicate to the compiler that it does not modify visible state. That is,
class Foo{
public:
void func() const{
std::cout << "Hello World!" << std::end;
}
};
will work fine. You put the const at the end of the function calls when they do not modify state (not completely true but more advanced for this post.)
So if you want to pass an object by const ref, you will only ever be able to call methods on it that have been declared non-state modifying. Please don't use const_cast unless you absolutely have to.
Also, don't forget to declare a variable of type Foo in your main body.
some_func(Foo &f); //if const declared will add the no of errors from 2 to 3
Wrong syntax.
Here is what you should be doing:
Foo f; //f is an object of type Foo
some_func(f); //pass the object to the function.
here is code which print "c++" in binary form and at the same time measure time
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
unsigned int t = clock();
string c = "c++";
int t=0;
for (int i=0;i<c.length();i++){
t = (int) c[i];
while (t!=0){
cout << t % 2 <<endl;
t >>= 1;
}
}
unsigned int end = clock();
cout << end-t << endl;
return 0;
}
but here is mistake
1>------ Build started: Project: name_of_c++, Configuration: Debug Win32 ------
1> c++_name.cpp
1>c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(11): error C2371: 't' : redefinition; different basic types
1> c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(7) : see declaration of 't'
1>c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(12): warning C4018: '<' : signed/unsigned mismatch
1>c:\users\david\documents\visual studio 2010\projects\name_of_c++\c++_name.cpp(16): error C2059: syntax error : '>='
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Look at these two lines:
unsigned int t=clock();
int t=0;
These are both in the same scope, and both define a variable t. This is not allowed in C++!
In case you are having trouble parsing the error message, when you get something like:
c++_name.cpp(11): error C2371: 't' : redefinition; different basic types
The number in parenthesis (11) tells you the line where the error occurred.
You know, compiler prints line numbers for errors.
Here is a problem:
unsigned int t=clock();
string c="c++";
int t=0;
First you declare t as unsigned int, and then you declare it as int.
you have declared t as unsigned int first here:
unsigned int t=clock();
and then defined again here as int
int t=0;
You can use a different variable name for the second one to get rid of this error.