Rosanswers logo

Hi there, I am new to ros and having a bit of problem when using subscribers. Here is some lines of my code and it is for leader following:

main(int argc, char **argv) {

ros::init(argc, argv, "mycontrol_1");

ros::NodeHandle n;

ros::Subscriber h_sub = n.subscribe("/uav1/sonar_height",1000,hcontrol);

switch (squad_leader_no){

case 1:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav1/split_cmd", 1000, getsplitcmd);


case 2:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav2/split_cmd", 1000, getsplitcmd);


case 3:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav3/split_cmd", 1000, getsplitcmd);


case 4:

  {ros::Subscriber splitcmd_sub = n.subscribe("/uav4/split_cmd", 1000, getsplitcmd);



// loop rate of 35Hz

ros::Rate cycle(35);


In above case, subscription fails. However, when I pull the subscriber out of the switch-case statement, it subscribes successfully. Could anybody explain this if know why, please? Thank you in advance.

Originally posted by PJ on ROS Answers with karma: 30 on 2014-08-11

Post score: 0

Original comments

Comment by ahendrix on 2014-08-11:
This is a duplicate of http://answers.ros.org/question/189706/subscriber-and-if-elseswitch-case-statement/ . Please do not ask duplicate questions.


1 Answer 1


Rosanswers logo

Your problem has nothing to do with ROS, but rather C++. From your code, your subscription is not failing, but the object you're instantiating within each "case" statement is going out of scope straight after you instantiate the object.

Try the following: Add ros::Subscriber splitcmd_sub; just below ros::Subscriber h_sub = ... and then change your "case" statements to only have splitcmd_sub = n.subscribe(...);.

That will solve your problem. :-)

Originally posted by Murilo F. M. with karma: 806 on 2014-08-11

This answer was ACCEPTED on the original site

Post score: 1

Original comments

Comment by PJ on 2014-08-14:
Thanks a lot, Murilo, but I have closed this question due to duplication. :)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.