C++ compiler not throwing error for undeclared variable - c++

I tried to search for this specific problem and did not find anythying concrete.
I was using an undeclared variable in my program and the compiler did not complain, it just gave a warning and the program runs fine. My gcc version is 4.1.2
Below is a sample program I wrote to reproduce this, the variable "index" is not declared, why is the compiler treating "index" as a function and where does it find the definition of the function?
#include <iostream>
using namespace std;
int testfunction()
{
try {
cout << "inside testfunction method\n";
return 2;
} catch(...) {
cout << "caught exception" << index << endl;
}
return 1;
}
int main()
{
cout << "Testfunction return value : " << testfunction() << endl;
}
Compiling:
~ g++ throwreturntest.cpp
throwreturntest.cpp: In function ���int testfunction()���:
throwreturntest.cpp:11: warning: the address of ���char* index(const char*, int)���, will always evaluate as ���true���
Running :
~ ./a.out
inside testfunction method
Testfunction return value : 2

Looks like index is the name of a GCC builtin function:
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
So it is already declared, just not by you.

The compiler is quite verbose about the situation. It things that index is an address of a function with signature
char *index(const char *s, int c);
See man index(3). The corresponding header is somewhere in the chain of <iostream>

Related

C++ handles an uninitialized field in a strange way

The sample below shows reading an uninitialized field a.i1 in two ways. The first call does not compile. However, calling a.donothing() that does not do anything, the original call compiles fine and prints the default value 0. Why is this inconsistency?
I am using Visual Studio Community 2015, the compiler output is as follows:
Severity Code Description Project File Line Suppression State
Error C4700 uninitialized local variable 'a' used
class A {
public:
int i1;
void donothing() {}
};
int main() {
A a;
cout << "main1: " << a.i1 << endl; // compile fails
a.donothing();
cout << "main2: " << a.i1 << endl; // prints 0 (default)
return 0;
}
Compiler is doing what it ought to do. You can fix it like this (as one solution out of many):
class A {
public:
A(int i = 0) : i1(i) {}
int i1;
void donothing() {}
};
In both cases a warning must be issued, at most. The fact that calling donothing cancels the error is a clear indication that this is a bug. You can report it at Microsoft Connect.
A simple workaround for this problem is to change the declaration to A a{};.
You can test your code on different compilers at Compiler Explorer.
[EDIT] The warning message C4700 is treated as an error if Security Development Lifecycle is turned on (/sdl).
Depends on the compiler, the compiler should supply a default constructor that will initialize your members with a default value. But this behavior is not dependable. Since C++11 you can say ClassName()=default; The best practice is to prove your own default constructor.
Your code never had any compiler errors with g++ 5.4.0
#include <iostream>
using namespace std;
class A {
public:
//A() : i1(0) { } // compiler will provide this if you don't write anything
// since C++ 11 you can also say A() = default;
A() = default;
int i1;
void donothing() {}
void writeMember() const { cout << "i1 value: " << i1 << endl; }
};
// better provide a signature for the main function
int main(int argc, char* argv[]) {
A a;
a.writeMember();
cout << "main1: " << a.i1 << endl; // compile fails
a.donothing();
cout << "main2: " << a.i1 << endl; // prints 0 (default)
return 0;
}
To compile the above code stored in testclass.cpp
g++ -std=c++11 -o testclass testclass.cpp
By using the C++11 default I got
i1 value: 4196976
main1: 4196976
main2: 4196976
If you comment out A()=default; this will rely on the compiler provided initializer, or the compiler may be lazy and not doing anything for performance reasons. You get
i1 value: 4196944
main1: 4196944
main2: 4196944
If you uncomment the line after public: you should consistently get 0
This illustrates the importance of adhering to good conventions of alway provide your own default constructor. The compiler maybe doing the right thing by not assigning any particular value to your member because you may assign another value in the next operation. This can save one operation. The member will be simply allocated on the stack, in that case the member got a random value. If you run this code on a different computer you will for sure get a different value.

C++ struct testing

Hi I am new to C++ and testing a structure in a c++ code in dev-c++. but it is not compiling and giving errors .
It is working well with .h extensions in pre-processor directives in dev-c++. so i Dont think so it carries .h extension problems
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
struct car
{
const int MAX=10;
char model[MAX];
char spare_part[MAX];
float cost;
}
int main()
{
car BMW ;
BMW.model[MAX]="SLR-8 S";
BMW.spare_part[MAX]="SILENCER";
BMW.cost=175.56F;
cout << setw(50) << "\n\n WELCOME TO SHOWROOM" << endl << endl;
cout << "CAR MODEL: " << BMW.model[MAX] << endl;
cout << "SPARE PART: " << BMW.spare_part[MAX] << endl;
cout << "COST OF PRODUCT: " << BMW.cost[MAX] << endl;
return 0;
}
Compiler logs are:
Compiler: Default compiler
Executing g++.exe...
g++.exe "D:\cdev\projects\structure.cpp" -o "D:\cdev\projects\structure.exe" -I"D:\cdev\Dev-Cpp\lib\gcc\mingw32\3.4.2\include" -I"D:\cdev\Dev-Cpp\include\c++\3.4.2\backward" -I"D:\cdev\Dev-Cpp\include\c++\3.4.2\mingw32" -I"D:\cdev\Dev-Cpp\include\c++\3.4.2" -I"D:\cdev\Dev-Cpp\include" -L"D:\cdev\Dev-Cpp\lib"
In file included from D:/cdev/Dev-Cpp/include/c++/3.4.2/backward/iostream.h:31,
from D:\cdev\projects\structure.cpp:1:
D:/cdev/Dev-Cpp/include/c++/3.4.2/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the <X> header for the <X.h> header for C++ includes, or <iostream> instead of the deprecated header <iostream.h>. To disable this warning use -Wno-deprecated.
D:\cdev\projects\structure.cpp:6: error: ISO C++ forbids initialization of member `MAX'
D:\cdev\projects\structure.cpp:6: error: making `MAX' static
D:\cdev\projects\structure.cpp:13: error: new types may not be defined in a return type
D:\cdev\projects\structure.cpp:13: error: extraneous `int' ignored
D:\cdev\projects\structure.cpp:13: error: `main' must return `int'
D:\cdev\projects\structure.cpp: In function `int main(...)':
D:\cdev\projects\structure.cpp:16: error: `MAX' undeclared (first use this function)
D:\cdev\projects\structure.cpp:16: error: (Each undeclared identifier is reported only
once for each function it appears in.)
Execution terminated
Values in stuct should be initialized in a constructor, or should be static. Like:
struct car
{
static const int MAX=10;
...
There is a semicolon missing after the struct definition. It should be like:
struct car
{
static const int MAX=10;
char model[MAX];
char spare_part[MAX];
float cost;
};
Check your semicolons. One is required after the closing } of the struct.
Also, declare the MAX variable static, i.e.
{
static const int MAX=10;
but the compiler tells you that one quite nicely...
And the third error comes from the fact that you declare MAX inside car, you'd have to reference it accordingly as car::MAX. But actually, the whole BMW.model[MAX]="SLR-8 S"; statement doesn't really make sense. That would mean 'assign the string "SLR-8 S" to the character after the last one in BMW.model' (for a char[MAX], the valid indices start at 0, and go to (MAX-1)!). Best use std::string instead of char model[MAX], that's by far easier to handle! E.g.:
struct car
{
std::string model;
Then you can simply say
BMW.model="SLR-8 S";

C++ callback function run time error

I have a function that accepts function pointer as an argument and calls the function pointer as shown below.
int foo (int a, int(*calc)(int))
{
int y;
// ....
// calling calc function via callback
(*calc)(y);
}
The calc function to be called back looks like
int calc(int x)
{
// ....
cout << x;
checkValue(x);
}
function foo is placed in a.cpp and function calc() and checkValue() are defined in files b.cpp and c.cpp. My problem is calc() executes fine until the cout statement and fails to call checkValue() function. The crash report I received is:
symbol lookup error:..... undefined symbol: _ZNSaIcEC1Ev, version GLIBCXX_3.4
How can I solve this problem?
The symbol _ZNSaIcEC1Ev is the mangled name for the std::allocator<char>::allocator() zero-argument constructor (I determined this using the c++filt(1) program). The error message "symbol lookup error:..... undefined symbol" relates to dynamic linking and has nothing to do with calling a function through a function pointer.
Your error almost certainly lies somewhere else. You're probably getting confused about the location of the error due to stdout buffering -- strings are getting printed to stdout, but you're not seeing them show up because they're getting buffered in memory, and then the program crashes before they're displayed. To avoid that, you need to make sure to flush the output after every print statement (e.g. by inserting std::cout << std::endl or std::cout << std::flush or explicitly calling std::cout.flush()), or by using std::cerr instead of std::cout, which is unbuffered by default.
#include <iostream>
using namespace std;
int calc(int x){
cout<< "calc:" << x << endl;
}
int CALC(int x) {
cout << "CALC: " << x << endl;
}
int foo (int a, int(*callback)(int)){
cout << "Calling calc on:" << a << endl;
(*callback)(a);
}
int main() {
cout << "START" << endl;
foo(5, calc);
foo(6, CALC);
}
This works fine for me.
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)
Note: I removed your "checkValue(x)" call, the issue could be in there...

C++ What should I do instead of global variables? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
C++: Easiest way to access main variable from function?
I need to get my variable "input" from my main function in a.cpp to another function named check in b.cpp. I looked into it on Google and this forum/thingy, and I found you could do it with global variables using extern, but that's it's also bad to use those and I couldn't find an answer to what an alternative is? How should I transfer the data in the variable to the other function without using globals?
Code of how I got arguments to work.
(What I'm trying to do here is a console "manager" for solutions of project Euler which I can call to solve/view via input, I started working on the code 40 mins ago.)
main.cpp
#include <iostream>
#include <windows.h>
#include "prob.h"
using namespace std;
int check(string x);
int main()
{
string input = "empty";
clear();
cout << "Welcome to the Apeture Labs Project Euler Console! (ALPEC)" << endl << endl;
cout << "We remind you that ALPEC will never threaten to stab you" << endl;
cout << "and, in fact, cannot speak. In the event that ALPEC does speak, " << endl;
cout << "we urge you to disregard its advice." << endl << endl;
cin >> input;
cin.get();
check(input);
cout << input << endl;
cin.get();
return 0;
}
prob.h
#ifndef PROB_H_INCLUDED
#define PROB_H_INCLUDED
int main();
int clear();
int check();
int back();
int P1();
int P2();
int P3();
int P4();
#endif // PROB_H_INCLUDED
back.cpp
#include <iostream>
#include <windows.h>
#include "prob.h"
using namespace std;
int clear()
{
system( "#echo off" );
system( "color 09" );
system( "cls" );
return 0;
}
int check( string x )
{
if( x == "help" );
if( x == "empty" )
{
cout << "And.... You didn't enter anything..." << endl << endl;
}
else
{
cout << "Do you have any clue what you are doing? " << endl << endl;
}
return 0;
}
By passing the data as an function argument.
For example:
int doSomething(int passedVar)
{
}
int main()
{
int i = 10;
doSomething(i);
return 0;
}
Note that the function definition may reside even in a different cpp file. The main only needs to see the function declaration, and the linker shall link the function definition correctly.
Usually, one would add the function declaration in a header file and include the header file in main, while providing the function definition in another cpp file.
The code you show has number of problems:
You do not need to declare main in the header file.
Your function declaration and definition of check() do not match. Your header file says it takes no argument and you define a the function definition to take one argument. Obviously, they don't match. As they stand now they are two completely different functions.
As the compiler sees it you declared one function who's definition you never provided and you defined another function in the cpp file. Thus the function declared(one with no parameters) was never defined and hence the definition not found error.
Andrei Tita is absolutely correct. If you have a "value" in one module (e.g. "main()" in a.cpp), and you wish to use that value in a function (e.g. "foo()" in b.cpp) ... then just pass that value as a function argument!
As your programs become more sophisticated, you'll probably start using classes (instead of functions) .

How do I imitate the Microsoft version of __FUNCTION__ using gcc?

When I use the __FUNCTION__ macro/variable to print out debugging information, there seems to be a difference in what it outputs when using the Microsoft C++ compiler and gcc. For example, using the following trivial code:
class Foo
{
public:
void Bar(int a, int b, int c)
{
printf ("__FUNCTION__ = %s\n", __FUNCTION__);
}
};
int main (void)
{
Foo MyFoo;
MyFoo.Bar();
return 0;
}
Using the Microsoft Visual C++ compiler, I get
__FUNCTION__ = Foo::Bar
whereas when compiling using gcc (in this case on the Mac), I get
__FUNCTION__ = Bar
The second example is not ideal because I quite often have several classes with, say, Init() and Uninit() methods and in a debug output trace its virtually impossible to tell which one of these has been called as the class name will be missing. Now, I know you can use the __PRETTY_FUNCTION__ in place of __FUNCTION__ to get something like
__PRETTY_FUNCTION__ = void Foo::Bar(int, int, int)
Which is fine, but its a bit too verbose for what I need and gets a bit long for functions with a lot of parameters.
So my question is (at last), is there any way to get the output to look like simply Foo::Bar using gcc, as in the example above?
If you are using it for tracing, you can always use typeid(T).name() and just conditionally compile per platform. Certainly not as convenient as the macro, but it could work.
Vaguely similar to __CLASS__ macro in C++
The function-name sanctioned by the standard is defined as follows:
static const char __func__[] = "function-name ";
Example:
#include <iostream>
namespace meh {
void foobar() { std::cout << __func__ << std::endl; }
};
struct Frob {
void foobar() { std::cout << __func__ << std::endl; }
static void barfoo() { std::cout << __func__ << std::endl; }
};
int main () {
std::cout << __func__ << std::endl;
meh::foobar();
Frob().foobar();
Frob::barfoo();
}
However, output with g++:
main
foobar
foobar
barfoo
However, that is valid C++ behaviour:
§ 8.4.1, 8: The function-local predefined variable __func__ is defined as if a definition of the form static const char __func__[] = "function-name ";
had been provided, where function-name is an implementation-defined string. It is unspecified whether such a variable has an address distinct from that of any other object in the program
I.e., you may not trust in its value. If you want to use non-portable extensions, have a look at a similar question: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__? .