I have a question regarding inline function.
#include <iostream>
using namespace std;
class A
{
public:
inline void fun()
{
int i=5;
cout<<i<<endl;
}
};
int main()
{
A a1;
int i = 2;
a1.fun();
cout<<i<<endl;
return 0;
}
In above program, when function fun() was called, the compiler should have made copy of this function and insert into main function body because it is inline.
So, I have a question, Why doesn't compiler give an error of variable int i; being re-declared?
You seem confused about scopes. They're not "within the same" scope
You can declare multiple variables with the same name at different scopes. A very simple example would be the following:
int main()
{
int a; // 'a' refers to the int until it is shadowed or its block ends
{
float a; // 'a' refers to the float until the end of this block
} // 'a' now refers to the int again
}
Inline expansion is not pure text replacement (as opposed to macros).
Whether a function is inlined or not has no effect on semantics Otherwise the program would behave differently depending on whether the function was inlined or not, and return statements would not behave properly at all.
Related
I recently picked up C++ and decided to try out making a function. However, I've run into a problem with my function func() where, even if declared beforehand, it only works if it's placed before the main() function.
If I place it after the main() function, the system tells me there is "no matching function for call to func".
Note: the functionfunc2 on the other hand works even if placed before or after the main() function.
So here's the code :
#include <stdio.h>
#include <iostream>
void func2();
int func();
int main()
{
int y=2;
std :: cout << "Hello World\n" << func(y) << "\n";
func2();
return 0;
}
int func(int x)
{
x *= 2;
return x;
}
void func2()
{
std :: cout << "Hello there";
}
In C language, the declaration int func(); means a function with an unspecified number of arguments of any type, returning a int.
In C++ language, the same declaration int func(); means a function without any arguments, returning a int.
And therefore, in C++, the definition of func with an argument of type int is an overload. For the compiler, it is a different function, which in the original code is not declared before use, so an error is emitted.
But in C, it would be perfectly legal.
int func();
and
int func(int x)
See the difference? The first one should be
int func(int x);
You told the compiler that func was a function with no arguments, then when you tried to call it with one argument the compiler said 'no matching function'.
I have a file named test.cc
#include <stdio.h>
int doit(){
return 4;
}
namespace abc {
int returnIt(int a){
return a;
}
}
I can use doit(), but how can I use this function in namespace in my main.cc without using .h file:
using namespace abc;
int doit();
int main(int argc, const char * argv[]) {
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}
You can call functions by first declaring them. Example:
namespace abc {
int returnIt(int a); // function declaration
}
int main() {
abc::returnIt(3); // the declared function can now be called
Note that the declaration must be exactly the same as used elsewhere in the program. To achieve identical declarations across translation units, it is conventional to put the declaration into a separate file (called a header) and include that file using the pre-processor whenever the declaration is needed.
All you need is to simply write the functions before the main function. That way, the compiler has processed the function prototypes by the time it encounters them in main and can validate the function call.
int doit()
{
return 4;
}
int returnIt(int a)
{
return a;
}
int main(int argc, const char * argv[])
{
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}
In general, avoid using namespace;. It makes for code that can be broken or be rendered less readable due to incorrect variable/function usage. That is because too many symbols can occupy the same (global) scope.
If another library needs to used, as user4581301 pointed out, then it may be simpler to use eerorika answer/method.
I'm using VS 2013, for some reason in a C++ console application a simple function declaration will not work. What is going on?
I have #include iostream and the code is inside the int main () {...} body.
-TSR
UPDATE:
Here is the full program
Look at the comment in my program. You should write functions outside of the main method.
/* Wrong code
-----------------------------------------
*/
#include <iostream>
int main()
{
int printmessage ()
{
}
}
/* Correct code
----------------------------------------
*/
#include <iostream>
int printmessage ()
{
}
int main()
{
}
You are not allowed to define a function within another function, although you are allowed to declare one. So something like this is allowed:
int main()
{
void func1() ; // function declaration but not definition.
}
void func1()
{
//...
}
but this is probably what makes more sense for you:
int printmessage()
{
//...
}
int main()
{
}
Function definitions are only allowed in the namespace or class scope, from the draft C++ standard section 8.4 Function definitions paragraph 2 says:
[...]A function shall be defined only in namespace or class scope.
You cannot have a function definition inside the main loop. You can either use function prototyping before the main(int argc, char** argv) or define the function before the main.
// Either define your function here
void Foo() { }
// Or use this prototyping
void Bar();
int main ()
{
// Call your function here
Foo();
return EXIT_SUCCESS;
}
void Bar() { }
Hope this helps.
For the declaration of function inside another function, it is just the backward compatibility with C programming. I doubt if anyone ever use this anymore. Plus, this is C++ not C
New to C++. Just making a simple struct/array program. Why can't I pass an array of structs like I intend to here?
int NumGrads();
int main()
{
struct Student {
int id;
bool isGrad;
};
const size_t size = 2;
Student s1, s2;
Student students[size] = { { 123, true },
{ 124, false } };
NumGrads(students, size);
std::cin.get();
return 0;
}
int NumGrads(Student Stu[], size_t size){
}
I appreciate that it must be something to do with passing by either reference or value, but surely if I've defined it in main(), I shouldn't be getting an error with the parameter of NumGrads?
Your struct is defined inside your main, and your NumGrads function is defined outside of main.
This means your struct is defined outside the scope of where your function can see it.
Move the definition of your struct above main and your problem is resolved.
Student is defined in main().
Define it outside of main so that it's in the same scope as NumGrads:
struct Student
{
int id;
bool isGrad;
};
int main()
{
...
}
The struct definition is local to main. Nothing outside of main can see it, including your NumGrads definition. Having a struct definition inside a function is not a very common thing to do - typically you would have it at namespace scope.
Also your NumGrads declaration doesn't agree with the argument types of the definition.
// Define Student at namespace scope
struct Student {
int id;
bool isGrad;
};
int NumGrads(Student[], size_t); // The argument types are now correct
int main()
{
// ...
}
int NumGrads(Student Stu[], size_t size){
}
struct Student is declared inside of main, so int NumGrads cannot see it. Furthermore, the function is undeclared at the point you call it in main. At that point, the only available declaration is int NumGrads(), which is a different function.
I am starting to learn C++ and Qt, but sometimes the simplest code that I paste from a book results in errors.
I'm using g++4.4.2 on Ubuntu 10.04 with QtCreator IDE. Is there a difference between the g++ compiler syntax and other compilers? For example when I try to access static members something always goes wrong.
#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;}
};
int main()
{
int A::x = 100; // error: invalid use of qualified-name 'A::x'
cout<<A::getX(); // error: : undefined reference to 'A::x'
return 0;
}
I think it's exactly the same as declared here and here (isn't it?). So what's wrong with the above code?
You've declared the static members fine, but not defined them anywhere.
Basically what you've said "there exists some static member", but never set aside some memory for it, you need:
int A::x = 100;
Somewhere outside the class and not inside main.
Section [9.4.2]
Static Data Members
The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator
You need to define the static member variable of the class outside the class as static member variables require declaration as well as definition.
#include <iostream>
using namespace std;
class A
{
public:
static int x;
static int getX() {return x;}
};
int A::x; // STATIC MEMBER VARIABLE x DEFINITION
int main()
{
A::x = 100; // REMOVE int FROM HERE
cout<<A::getX();
return 0;
}
Try:
#include <iostream>
using namespace std;
class A
{
public:
// This declares it.
static int x;
static int getX(){return x;}
};
// Now you need an create the object so
// This must be done in once source file (at file scope level)
int A::x = 100;
int main()
{
A::x = 200;
// Notice no 'int' keyword before A::x on this line. You can modify A::x
cout<<A::getX(); // Should work
return 0;
}
The definition of static member variables must live at file scope, i.e. outside all functions, etc.
Try this example:
#include<iostream>
using namespace std;
class check
{
static int a;
public:
void change();
} ;
int check::a=10;
void check::change()
{
a++;
cout<<a<<"\n";
}
int main()
{
int i,j;
check c;
check b;
c.change();
b.change();
return 0;
}
Now you have worked out how to use static class members I will advise you that you should generally use them only in the following circumstances:
For use in templates. So in your example you could have GetX() in different classes and in a template somewhere you would use
template< typename T >
int func()
{
return T::GetX();
}
although obviously more elaborate. But here your static function being in a class serves a purpose.
Where the function needs access to the class, i.e. to private members. You could make it a friend but you may as well make it static. Often the case in callbacks.
The rest of the time you can probably use compilation-unit level functions and variables which has the advantage of taking your members out of the header (particularly if they are private). The less implementation detail you give the better.
You can use the inline keyword since c++ 17 in front of static members to avoid a definition outside of class scope. Your code should now look like this:
#include <iostream>
using namespace std;
class A
{
public:
inline static int x;
static int getX() {return x;}
};
int main()
{
A::x = 100; //Works now
cout<<A::getX()<<'\n';
return 0;
}
Case 1: static variable
As we all know, defining a static variable inside a class which will throw compilation error. E.g. below
class Stats
{
public:
static int AtkStats[3];
*static int a =20;* // Error: defining a value for static variable
};
int Stats::AtkStats[3] = {10, 0, 0};
Output:
error: ISO C++ forbids in-class initialization of non-const static member 'Stats::a'
Case 2: const static variable
For const static variable, we can define a value either inside a class or Outside class.
class Stats
{
public:
static const int AtkStats[3];
static const int a =20; // Success: defining a value for a const static
};
const int Stats::AtkStats[3] = {10, 0, 0};
const int Stats::a = 20; // we can define outside also
Output:
Compilation success.