Robot CPP Programming Basics-02 Variables Variables

Robot CPP Programming Basics-01 The first program Hello World

The basic code can be learned with the help of artificial intelligence tools.


C++ 

#include<iostream>

using namespace std;

main()
{
    //Declaring an integer type variable A, allocates 4 bytes of memory.
    int A=4;

    cout<<A <<endl;
    //Prints the address of the variable A.
    cout<<&A <<endl;

    /*
        1. Variables cant have the same name.
        2. Variable name cant start with a number.
        3. Variable name should not contain spaces.
        4. Variable name should be self-descriptive.
        5. Variable name can't have special characters or keywords.
    */

    //Re-initialization of A.
    A=10;
    cout<<A <<endl;
    cout<<&A;
}

The code basically does the following:

  1. Declare a  A variable of type Integer named and initialize it to  4. In C++, int types typically occupy 4 bytes of memory space.
  2. Use  cout the statement to output  A the value of the variable, ie  4.
  3. Use  cout statements to output  A the address of a variable, that is, the location of the variable in memory.
  4. By means of comments, some rules and precautions about variable naming are listed.
  5. Reinitializes  A the value of  the variable 10.
  6. Use  the statement to output  the value of  cout the variable again  , ie .A10
  7. cout Finally, use the statement  again  to output A the address of the variable.

The code is parsed.

basic concept:

C++ variables are a mechanism for storing data in a program. Variables are identifiers used to store and manipulate data. The following is a detailed introduction to C++ variables:

  1. Variable naming: variable names can be letters, numbers, underscores, and must start with a letter or underscore. Variable names usually use camel case or underscore nomenclature.
  2. Variable type: A variable must specify its type when it is declared. C++ has many built-in types, including integers, floats, chars, Booleans, and more. In addition, you can also use custom types, such as structures, classes, and so on.
  3. Declaration of variables: In C++, variables must be declared before they are used in the program. A declaration tells the compiler the name and type of the variable so that the compiler knows how to allocate memory space for the variable.
  4. Assignment of variables: After declaring a variable, it must be initialized to a value. Values ​​can be assigned to variables using the assignment operator (=).
  5. Scope of variables: The scope of variables refers to the visibility and life cycle of variables in the program. There are two types of scopes in C++: local and global. Local scope limits the visibility and lifetime of a variable to only be available within the block of code in which it is defined. Global scope makes variables visible throughout the program.
  6. Constant: A constant is a special type of variable that represents an immutable value. In C++, constconstants are declared using keywords.
  7. Variable type conversion: In C++, implicit type conversion and explicit type conversion can be performed. Implicit type conversion occurs when the compiler automatically converts a value of one type to another, such as converting an integer to a floating point number. Explicit type conversions use type conversion operators (eg static_cast, , dynamic_castetc.) to explicitly convert a value of one type to another.

The above is a detailed introduction to C++ variables. Mastering these concepts is very important for writing efficient C++ programs.

C++14 is the latest standard for the C++ language, and it introduces some new features and improvements regarding variables. Here are some details about variables in C++14:

  1. auto keyword: C++14 introduces the auto keyword to automatically infer the type of a variable. Using the auto keyword simplifies the type declaration of variables, especially when using complex expressions or nested containers.

  2. List initialization and variable declaration: C++14 supports the use of curly braces ({}) for list initialization, and the initial value can be directly assigned to the variable without using the assignment operator. For example:

 
 

cpp复制代码

int a = {10};
std::string str = {"Hello World"};
  1. Initialization list constructor: C++14 introduces an initialization list constructor, which allows the use of an initialization list to initialize member variables in a class constructor. For example:

 
 

cpp复制代码

class MyClass {
public:
MyClass(int a, int b) : m_a(a), m_b(b) {}
private:
int m_a;
int m_b;
};
  1. Generalized delegate expressions: C++14 introduces generalized delegate expressions (Generalized Delegate Expressions), which allow the use of more flexible expressions to construct delegate expressions.
  2. Static assertion: C++14 introduces static assertion (Static Assert), which is used to check whether conditions are met at compile time. The compiler will generate an error or warning if the condition is not met.
  3. Rvalue references and move semantics: C++14 introduces rvalue references (Rvalue Reference) and move semantics (Move Semantics) to optimize resource management and performance.

The above is a detailed introduction to variables in C++14. These new features and improvements improve code readability and performance, and make C++ more modern and flexible.

C++20 is the latest standard of the C++ language and introduces some new features and improvements regarding variables. Here are some details about variables in C++20:

  1. Type inference and auto keyword: C++20 expands the function of type inference, so that the type of the variable name can be omitted when the variable is declared, and only the variable name can be used. This makes the code more concise and readable.

 
 

cpp复制代码

auto x = 10; // 推断x的类型为int
auto v = {1, 2, 3}; // 推断v的类型为std::initializer_list<int>
  1. Structured binding: C++20 introduces structured binding (Structured Binding), which allows member variables of a structure or union to be directly assigned to multiple variables.

 
 

cpp复制代码

struct Point {
int x;
int y;
};
Point p;
auto [x, y] = p; // 将p的x和y成员变量分配给x和y变量
  1. Range-based for loop: C++20 introduces a range-based for loop (Range-based for loop), allowing the elements of a container or array to be directly traversed in a for loop.

 
 

cpp复制代码

int arr[] = {1, 2, 3, 4, 5};
for (int elem : arr) {
// 直接访问arr的每个元素
std::cout << elem << std::endl;
}
  1. Initialization list constructor: C++20 continues to support initialization list constructors, allowing the use of initialization lists in class constructors to initialize member variables.
  2. The concept keyword: C++20 introduces the concept keyword, which is used to define the concept of a type and to constrain the type of a template parameter. This helps to improve the readability and maintainability of the code.
  3. if constexpr and if let: C++20 introduces if constexpr and if let, which are used for conditional judgment and pattern matching at compile time, which helps to write more concise and efficient code.
  4. coroutines: C++20 introduces coroutines (Coroutines), which is a control flow mechanism that allows functions to suspend execution during execution and return control to the caller, and then re-enter execution at a certain point. Coroutines can be used to implement functions such as asynchronous programming and generators.

The above is a detailed introduction to variables in C++20. These new features and improvements further improve code readability and performance, making C++ more modern and flexible.


Arduino

int A = 4;  // 声明一个整数类型的变量 A,并初始化为 4  
  
void setup() {  
  Serial.begin(9600);  // 初始化串口通信,波特率为 9600  
}  
  
void loop() {  
  Serial.print(A);  // 输出变量 A 的值到串口  
  Serial.print(" ");  // 输出一个空格  
  Serial.print(&A);  // 输出变量 A 的地址到串口  
  Serial.println();  // 输出一个换行符  
  
  delay(1000);  // 延时 1 秒  
  
  A = 10;  // 重新初始化变量 A 的值为 10  
}

In the Arduino IDE, you can view the output results through the serial monitor. In  loop() the function, after outputting the value and address of the variable A and reinitializing the value of A each time, it is used  delay(1000) to delay 1 second so as to observe the change of the output result.


ROS1

#include <ros/ros.h>  
  
int main(int argc, char **argv)  
{  
    // 初始化ROS节点  
    ros::init(argc, argv, "my_node");  
  
    // 创建ROS节点句柄  
    ros::NodeHandle nh;  
  
    // 声明一个整数类型变量A,分配4个字节的内存空间  
    int A = 4;  
  
    // 发布变量A的值到"chatter"话题  
    ros::Publisher chatter_pub = nh.advertise<std_msgs::Int32>("chatter", 1000);  
  
    // 创建标准消息类型:整数类型(32位)  
    std_msgs::Int32 msg;  
    msg.data = A;  
  
    // 发布消息到"chatter"话题  
    ros::Rate loop_rate(1);  
    while (ros::ok()) {  
        msg.data = A;  
        chatter_pub.publish(msg);  
        ros::spinOnce();  
        loop_rate.sleep();  
    }  
  
    return 0;  
}

The above code is a C++ node for ROS1, which uses the ROS C++ library. Here is a detailed explanation of the code:

  1. #include <ros/ros.h>: Introduce the ROS namespace and header files, which contain various functions and classes used in ROS.
  2. using namespace std;: introduces stda namespace so we can use functions and objects from the standard library directly without prefixing each one std::.
  3. int main(int argc, char **argv): The main function, where the execution of the program starts. It accepts two arguments: the number of command-line arguments ( argc) and the value of the command-line argument ( argv).
  4. ros::init(argc, argv, "my_node"): Initialize the ROS node. This is the first step every node in ROS must do. It accepts three arguments: the number and value of command-line arguments, and the node's name.
  5. ros::NodeHandle nh;: Create a node handle object nh. The node handle is a very important object in ROS, which provides a communication interface with the ROS system.
  6. ros::Publisher chatter_pub = nh.advertise<std_msgs::Int32>("chatter", 1000);: Create a chatter_pubPublisher object named "chatter" using the node handle and use advertisea function to associate it with the topic named "chatter". This publisher will std_msgs::Int32publish messages using the message type. The second parameter is the size of the publisher queue, which is set to 1000 here.
  7. std_msgs::Int32 msg;: Creates a message object named msgfor std_msgs::Int32posting to the "chatter" topic.
  8. msg.data = A;: Set msgthe data field of the message object to Athe value of the variable.
  9. chatter_pub.publish(msg);: Use the publisher object chatter_pubto publish the message object msgto the "chatter" topic.
  10. ros::Rate loop_rate(1);: Create a loop_raterate object called rate object and set it to publish messages every second (since the parameter is 1).
  11. while (ros::ok()): Create a loop that will be executed as long as the ROS system is running normally.
  12. ros::spinOnce();: Execute a ROS Spin main loop to process messages from the ROS system and call callback functions.
  13. loop_rate.sleep();: Call sleepthe function of the rate object, suspending execution for a period of time to keep the publishing frequency at once per second.
  14. return 0;: Return 0 to indicate the successful execution of the program.

In summary, the code creates a ROS node that periodically publishes an integer variable Ato a topic called "chatter". It uses the core components of ROS, including node handles, publishers, and message types, to interact with the ROS system.


……


 

Guess you like

Origin blog.csdn.net/ZhangRelay/article/details/132218661