theAlias
theAlias

Reputation: 396

Getting a line number from where a function returned

I have a cpp function which has multiple return points based on different flags set and different control flows. Is there a way to figure which return statement was used, without adding a line of debug for each return statement? (it is difficult to figure the return point just from the return value)

I already use RAII to log the entry and exit of the function. And I need the ability to log the line number where it returned.

I tried searching around for this but didnt find anything close to what i want

Upvotes: 1

Views: 243

Answers (4)

André Puel
André Puel

Reputation: 9179

You can use preprocessor macros:

#define return std::cerr << __FILE__ << ":" << __LINE__ << " return " << std::endl; return 

Right before your function definition. And:

#undef return

So you dont get a lot of log messages with returns that you are not concerned about.

Edit: By the way, if you have a RAII object that you are using to log it the function entry, you may do:

#define return entry_raii_object.exited_at(__LINE__); return

Dont forget to undef later. I personally would prefer a different keyword for logged returning, like #define logged_return ...; return

Upvotes: 1

Mohit Jain
Mohit Jain

Reputation: 30489

Change return_type fun(args) to pair<return_type, unsigned int> fun(args) and return val with return make_pair<return_type, unsigned int>(val, __LINE__)

Upvotes: 3

Andrew_CS
Andrew_CS

Reputation: 2562

One thing you could do is change the return type of the method to a Tuple.

One of the elements in the Tuple would be your original return value.

The second element could make use of the __LINE__ macro. You could either just return the line number or a String including the line number and other possible informative logging information about the return point.

Upvotes: 2

quantdev
quantdev

Reputation: 23793

You can use the standard __LINE__ predefined macro in your log statement :

From the gcc documentation :

This macro expands to the current input line number, in the form of a decimal integer constant. While we call it a predefined macro, it's a pretty strange macro, since its “definition” changes with each new line of source code.

Ideally, make your code simpler, reducing the number of return points, or include information about the return point in the returned value itself.

Upvotes: 1

Related Questions