ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | Q&A
Ask Your Question

When do we use & operator for defining a Subscriber's callback function

asked 2017-09-05 14:48:25 -0500

Frank Lee gravatar image

updated 2017-09-05 15:09:33 -0500

jayess gravatar image

Currently learning how to use ROS and arduino. However there's an example in the tutorial that stumps me.


/*   * rosserial Subscriber Example  * Blinks an LED on callback  */

#include <ros.h>
#include <std_msgs/Empty.h>

ros::NodeHandle  nh;

void messageCb( const std_msgs::Empty& toggle_msg){
  digitalWrite(13, HIGH-digitalRead(13));   // blink the led

ros::Subscriber<std_msgs::Empty> sub("toggle_led", &messageCb );

void setup()
  pinMode(13, OUTPUT);

void loop()


 * rosserial Servo Control Example
 * This sketch demonstrates the control of hobby R/C servos
 * using ROS and the arduiono
 * For the full tutorial write up, visit
 * For more information on the Arduino Servo Library
 * Checkout :

#if (ARDUINO >= 100)
 #include <Arduino.h>
 #include <WProgram.h>

#include <Servo.h> 
#include <ros.h>
#include <std_msgs/UInt16.h>

ros::NodeHandle  nh;

Servo servo;

void servo_cb( const std_msgs::UInt16& cmd_msg){
  servo.write(; //set servo angle, should be from 0-180  
  digitalWrite(13, HIGH-digitalRead(13));  //toggle led  

ros::Subscriber<std_msgs::UInt16> sub("servo", servo_cb);

void setup(){
  pinMode(13, OUTPUT);


  servo.attach(9); //attach it to pin 9

void loop(){

Comparing line 15 of blink and line 35 of ServoControl (basically the line with ros::Subscriber), I noticed that in blink the callback function has a & before it, which is missing from the ServoControl example. Why is this the case? When do I use the & sign, and what is it used for in this case?

edit retag flag offensive close merge delete


"& sign" -> "address-of operator".

gvdhoorn gravatar image gvdhoorn  ( 2017-09-05 15:00:30 -0500 )edit

@Frank Lee: You don't need to use the pre tags to format your code. Instead, please use the 101010 to format your code.

jayess gravatar image jayess  ( 2017-09-05 15:13:43 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2017-09-05 17:10:57 -0500

ahendrix gravatar image

In both cases, the subscriber constructor is taking a function pointer as the constructor argument.

The address-of operator is optional when using a function's name as a function pointer; , so both uses are correct and interchangeable.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2017-09-05 14:48:25 -0500

Seen: 377 times

Last updated: Sep 05 '17