Line structure of C++ for a newbie

I’ve had my Arduino Uno R4 for a few weeks and have gone through some of the projects listed in the manual that was included in the starter kit. So far I’m getting the projects are going just fine.

My problem is that I’m still confused by the structure of individual lines in C++. For example, I know how to write a the individual parts of a sentence in English are arranged and how a sentence in English is arranged differently than a sentence in Spanish. The C+ websites I look at tell what the commands mean and one group of code needs to come before others. But they don’t tell me why

Example 1: "#include ". What is “#” used? Why does it come right before “include”? Why is “iostream” surrounded by “<>”?

Example 2: "int main()”. If “int” refers to “integer” or a whole number, why does it come right before “main”? Why is it even used in conjunction with “main” at all since we aren’t asking for an answer in numbers in that statement?

Example 3: std::cout << "Hello World!”. If “std” is standard, why write “standard”? Why not just write “cout” to setup the output? And why the “::” right after "std"?

I hope my questions make sense.

Thanks for your help.

That is why I ask my students to attend classes regularly, even though the lecture notes are available on Google Classroom and can be downloaded and read at any time.

The same applies in your case. To get clear answers to your questions, you need to attend interactive online or practical lectures (with audio/video). These are the same types of questions I also raised when I started learning C about 25 years ago.

In any case, I will try to answer some of your questions, although I am not a serious/practicing C++ programmer.

@skybear
1. int main()
Q11: Whys is int before main()?
A11: In the English language, there are parts of speech, and each part has a name. Typically, the noun/subject appears before the verb. This is not a rule; rather, a style in which native speakers have been speaking and writing for hundreds of years. Over time, this usage has been documented and formalized as a rule in English grammar books.

Similarly, in the C++ language, there are tokens, and each token has a name and defined role. In the statement int main(), the tokens are int, main, (, and ). Since C++ is an artificial language, it has explicit syntax rules that dictate where each token must be placed. According to these rules, int (data type) appears before main() (function name), a convention that we learn and remember through practice.

Q12: Is there any other example where int goes before another token?
A12: int myData;. Here, myData is a variable/identifier. The int token is called data type, and it says that the myData variable can hold 16-bit data.

Q13: Can you explain with an example the meaning of int main() style?
A13: These are the codes to add two numbers:

void setup()
{
   int y1 = 0x1234;     //0x indicates that the next digits have 16-base (hex base)
   int y2 = 0x5678;
   int sum = y1 + y2;   //sum = 0x68AC
}

The above code can be written in the following style that resembles int main() structure. This formatting style has a specific advantage: the setup() function remains clean and uncluttered, instead of being populated with many lines of code. Here, I have pesented a simple example.

void setup()
{
   int y1 = 0x1234;     //0x indicates that the next digits have 16-base (hex base)
   int y2 = 0x5678;
   int sum = add(y1, y2);  //we call add() which returns int (16-bit) type result
}

int add(in p, int q)//p gets value of y1; q gets value of y2; add() returns 16-bit data
{
    int result = p + q;     //result holds 0x5678
    return(result);    //the value of ressult is assigned to variable sum
}

Given below an integrated version of the above fragmented codes, which you can upload and execute in UNOR4 board.

void setup()
{
  Serial.begin(9600);
  int y1 = 0x1234;     //0x indicates that the next digits have 16-base (hex base)
  int y2 = 0x5678;
  int sum = add(y1, y2);  //we call add() which returns int (16-bit) type result
  Serial.println(sum, HEX);  //shows: 68AC
}

void loop()
{
  
}

int add(int p, int q)//p gets value of y1; q gets value of y2; add() returns 16-bit data
{
  int result = p + q;     //result holds 0x5678
  return (result);   //the value of result is assigned to variable sum
}

@skybear
2. #include
Q21: What is the name of # symbol in C++ language?
A21: In C++, it is called preprocessor (marker).

Q22: What is the name of include token?
A22: It called preprocessor directive.

Q23: Then what is meaning of #include<SoftwareSerial.h>?
A23: The directive instructs the compiler to copy and paste all the contents of the file named SoftwareSerial.h (located in the working directory of your PC) at the top of the sketch or program. During compilation, the compiler performs optimization and retains only the code and structures that are actually needed by your sketch. A header file (*.h) may contain many functions, but typically only a few of them are used in your sketch.

Q24: Why is #include <SoftwareSerial.h> instead of
#include "SoftwareSerial.h"?
A24: You have asked the Compiler to include the file named SoftwareSerial.h in your sketch. This is not enough; you must give necessary instruction to the Compiler which folder to look first for the file. The pair of double quotes (" and ") tells the Compiler to look for the file in the Project Folder"; whereas, pair of angle brackets (< and >) instructs to look into System Folder.

3. Meaning of std::cout << "Hello World!"
................

.... in progress

Hi Golam,

No worries. Now that I know I’m not missing something obvious, I feel better. And I know what I need to look for, at least in general. I’ll see what there is locally.

What do you think about the three questions I listed?

Welcome to the forum

Computer programs are written in a language and like all languages there are rules to be followed so that the program can be understood by the compiler that turns it into machine language that is run on the processor

To answer your particular questions

The # in statements like
#include < myLibrary.h>
indicates to the compiler preprocessor that this action should take place before any compilation takes place. Doing so ensures that the code in the library is incorporated into the program

The data type before a function definition tells the compiler that it is expect that a value will be returned by the function and what data type that is. If a value is not to be returned by a function then you use the data type of void.

Your question about using cout brings up a couple of things. cout is a function in the std library and the :: indicates that. The cout function will only be included in the program if it is used. This save program space by only incorporating functions that are needed

main() is a function.
So, someday your program will end and return.
A function can return nothing (void) or something (like int).
I think it reports to the operating system... different numbers reflect why the function returned... My mac usually reports something like returned x, program ended successfull. I think this message is based on the returned number...

All the questions listed are about syntax.
Why a certain symbol? Why is it written in that specific place?

The reason is that the compiler (which produces the actual executable code for the microcontroller — the microcontroller does not understand C) was written to accept a certain syntax, and specific symbols were chosen to represent specific functionalities.

Could these symbols and the syntax have been different? Of course they could. A choice was made, and every programming language has its own particular syntax.

So what really matters is: what functionality, feature, or operation are we specifying at a given point?

The topics mentioned concern:

  • Compiler directives (preprocessor commands), which are not executable code but instructions telling the compiler to do something, for example to include external files, and which syntax to use.
  • Understanding what a function is (like main, but the same applies to any function), how it is defined, how it is used, and therefore discovering that a function can return a value whose type must be declared (that’s what int is, but it could also be void or something else).
  • Understanding variable scope within the code, which is where the :: operator comes in — it explicitly tells the compiler which scope should be considered for what follows.

At the beginning, it is always a wall of difficulty.

@skybear
If you're serious about learning a language, you'll have hundreds more questions like these. And I don't think the forum is the right place for them. People come here to sort out their specific problems. Those who help here are not hired workers, but enthusiasts who spend their time. It is unlikely that it will be respectful towards them if they explain to you what can and should be read in any С++ textbook.

Please, re-visit my post #2 to see the answers to your questions.

Right; in the case of main, if the int it returns is zero, that is considered "program ended OK", and any other number is the (primary) reason it failed. You may see this exit code when a build fails. The values are usually considered to be an 8-bit byte, so only up to 255; even though the range of an int is (much) larger.

On Arduino, the main part of main is essentially

setup();
for (;;) {
  loop();
}

which never returns, so the return value of main is moot.

Hi @b707 !

I think that it's ok to ask questions in the forum if one has difficulties to understand a specific topic.

The amount and content of the questions here leaves the impression that a lot of possibilities to get further information has not been leveraged....

@skybear : Most of your questions can be answered easily and understandable by an AI, e.g. ChatGPT. As you see above the amount of questions leads to many comprehensive answers for the same topic. Using an AI and investigating step by step might be more efficient and effective for you. Give it a try...

AI is helpful, and yet its answers are to be taken after rigorous scrutiny. For example: I submitted a piece of text to ChatGPT for modertaion. My text contains this formuala: 640 ((5-2.5 - 0.9)/.0025) which the AI has computed as:

I found differences when asking AI to solve mathematics (even simple) and providing information that is quite settled.

I also experienced that ChatGPT isn't reliable regarding mathematics. But you can even ask ChatGPT about better solutions: "Which AI is superior to ChatGPT regarding math tasks?" and you'll get helpful answers.

However, verifying responses is always a good idea, whether AI or Natural Intelligence... ;-)

FWIW I was told by cheatGPT that if I wanted good answers to questions like "what is 2 plus 3?" I would have to tell it to do the maths involved.

I asked if I could just say once at the beginning that anything that looked like it should be worked out with a calculator should in fact be so done.

No. So for that AI at least, you gotta say so in any prompt where it might decide to wing it.

a7

Gemini seems happy to accept a question like "What is 2 plus 3" and give the correct answer without further prompting

![image|690x221]

Interestingly, when to tell it to "Show code" it shows a Python script

Before 1986 I learned C from having a PC, getting a book on C at a college town used book store and trying a lot of things out. But I had done the same with Forth before and Basic before that and an intro to Fortran in 75.

After a while the similarities show through and how one language or another handles addresses or allows you to organize and operate on data for example teaches a lot.

Keep working with examples to fill your view. Read and research commands you are unfamiliar with (short studies) until you can follow what the code is doing..

just remember that the compiler may not agree with you. So mess with the examples to test your understanding, make or break. The deeper learning happens when you debug code, which can be like pulling teeth. Debugging is heavy lifting and when you’ve done enough, you take the next hard step and plan ahead.

Merry Christmas.

Sometimes you need to memorize before you learn. For example;

int main()

is short for...

int main(int argc, char *argv[])

... but for a little while, memorizing int main() works just fine... and it only gets better. Don't worry about your learning... it will come.

I have never, knowingly, programmed Arduino in C++. I use C for Arduino. Here is the original book on C...

@skybear

From that classic K&R's book referred in #17:

Or even entering your question into a plain old search engine:

I entered '#include c++' and got -

It's a rabbit hole for sure.

All Arduino programs are written in C++.

Never, have I ever, written C++, but I understand your meaning.

Same with my spoken language, which borrows from others, so there may be Italian, Russian, French, Spanish, German and Ethiopian in my speaking, but I am not thinking "need the word for coffee in Ethiopian" when ask for one.