In the spirit of the above, I have written the following code, but there are compilation error; as a result, the sketch is not uploaded. Therefore, unsigned int address = millis may be categorized as an invalid code.
I doubt that. Based on the error that I get the compiler simply does not know which Serial.println the code is referring to.
C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2026109-10752-15u4rv3.d25ug\sketch_nov9b\sketch_nov9b.ino: In function 'void setup()':
C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2026109-10752-15u4rv3.d25ug\sketch_nov9b\sketch_nov9b.ino:4:33: error: cannot resolve overloaded function 'println' based on conversion to type 'unsigned int'
unsigned int address = Serial.println;
^~~~~~~
/home/gilhad/Arduino/deleteme/sketch_nov09a/sketch_nov09a.ino: In function 'void setup()':
/home/gilhad/Arduino/deleteme/sketch_nov09a/sketch_nov09a.ino:6:26: warning: invalid conversion from 'long unsigned int (*)()' to 'unsigned int' [-fpermissive]
unsigned int address = millis;
^~~~~~
it writes "hello ", then the number of characers written (8 = hello + space + new line len), then address of millis (0x5F in words = 0xBE in bytes), exactly as expected.
Addresses for call/jump are in words on AVR, when dumping by sometools they are in bytes, yes may be confusing, but I did not wrote the tools.
Your example uses Serial.println instead, which is not address of anything.
unsigned int address = Serial.println;
as Serial.println is overloaded symbol and is substitued by compiler with something like _ZN14HardwareSerial5writeEh (or one of many another similar symbols) depending on the type and number of arguments used in the call.
But you did not specified, which function you want, as you did not provided argument types. Which the error stated, but you did not read:
/home/gilhad/Arduino/deleteme/sketch_nov09a/sketch_nov09a.ino: In function 'void setup()':
sketch_nov09a:6:33: error: cannot resolve overloaded function 'println' based on conversion to type 'unsigned int'
unsigned int address = Serial.println;
^~~~~~~
exit status 1
cannot resolve overloaded function 'println' based on conversion to type 'unsigned int'
which is totally different problem, that the warning in millis case.
Compiler would happilly offer the address, as in millis case, if you would give it enought data to resolve, which address (of many possible) you mean.
Remember, that you are programming in C++ with some libraries included automagically for your "convenience", even if Arduino authors talks about "Arduino language", to hide it (so you will not be "confused" by strange words like programming, C++, types of returned values and similars).
If the concept woks for the identifier of the millis() function, then it should work for the indentifiers for all other functions like Serial.println() ===> Serial.println.
No, the concept is defined clearly in C++ defining norms.
Regardles of what you want and what you did not read or understand.
The difference is, that digitalWrite() and Serial.println() are well defined function calls.
On the other hand only digitalWrite is well defined address while Serial.println is overloaded name without specification, which address (of many possible) you want to use.
The identifier of the millis() function is millis, and it works (with types warning).
The identifier of the Serial.println("hello") function is much complicated, as you must specify which of many variants of Serial.println functions family you mean.
AI generated example, I checked it and I think, it is OK
Question (in Czech)
jak v C++ (pro AVR, amega328p, v Arduinu) ziskam adresu pro overload function Serial.println("hello") a pro Serial.println(123), neco jako zhruba
unsigned long millisAddr = millis; // call millis()
unsigned long prlnConstCharPtr = Serial.println???; // Serial.println("hello")
unsigned long prlnInt = Serial.println???; // Serial.println(123)
Odpoved napis anglicky
AI Answer (in English)
In C++ (especially for AVR/Arduino), retrieving the address of an overloaded method and storing it in a plain integer type like unsigned long is highly restrictive due to how C++ handles member functions.
Unlike regular functions (such as millis), Serial.println is a non-static member function of the Print class. In C++, pointer-to-member functions cannot be directly cast to pointers or numeric types like unsigned long because they don't contain a simple memory address; they can also hold vtable offsets or structure data. On 8-bit AVR (ATmega328P), a regular function pointer is 16-bit (2 bytes), whereas member function pointers can be larger depending on the compiler.
However, we can bypass this limitation using two approaches: standard C++ pointers (safest) or compiler-specific hacks if you strictly need a numeric value.
Method 1: The Standard C++ Way (Recommended)
You should use a proper pointer-to-member-function syntax. To resolve the overload ambiguity, you must explicitly cast the function name to the correct signature.
Note that Serial is an instance of HardwareSerial, but its println methods are inherited from the Print class. Also, println(int) secretly has a second default argument base = DEC, so its signature is actually println(int, int).
#include <Arduino.h>
void setup() {
Serial.begin(9600);
// 1. Regular function pointer (millis) fits into a normal function pointer
// (On AVR, you can technically force-cast this into unsigned long)
unsigned long (*millisAddr)() = millis;
// 2. Pointer to println(const char*) -> for "hello"
size_t (Print::*prlnConstCharPtr)(const char*) =
(size_t (Print::*)(const char*)) &Print::println;
// 3. Pointer to println(int, int) -> for 123 (uses default base under the hood)
size_t (Print::*prlnInt)(int, int) =
(size_t (Print::*)(int, int)) &Print::println;
// --- HOW TO CALL THEM ---
// Calling millisAddr
unsigned long time = millisAddr();
// Calling member pointers requires an instance (Serial) and the (.*) operator
(Serial.*prlnConstCharPtr)("hello");
(Serial.*prlnInt)(123, DEC);
}
void loop() {}
Při použití kódu buďte obezřetní. (Be carefull with using this code.)
Method 2: Forcing them into unsigned long (The Pointer Hack)
If your architectural requirement strictly forces you to store these as a raw numeric unsigned long variable, standard reinterpret_cast will throw a compiler error.
To overcome this, you can extract the raw bytes of the member function pointer using a union or a raw memory copy (memcpy). Warning: This is undefined behavior in standard C++, but it compiles on AVR-GCC.
#include <Arduino.h>
// Helper function to extract address from member pointer into unsigned long
template <typename T>
unsigned long getMemberAddress(T memberPointer) {
unsigned long addr = 0;
// Copy the bytes of the pointer into our unsigned long variable
// On AVR, member pointers are typically 2 or 4 bytes depending on context
memcpy(&addr, &memberPointer, min(sizeof(memberPointer), sizeof(addr)));
return addr;
}
void setup() {
Serial.begin(9600);
// 1. Normal function pointer cast to unsigned long (Safe on AVR)
unsigned long millisAddr = (unsigned long)millis;
// 2. Extract raw addresses of the specific overloads
size_t (Print::*ptrStr)(const char*) = (size_t (Print::*)(const char*)) &Print::println;
unsigned long prlnConstCharPtr = getMemberAddress(ptrStr);
size_t (Print::*ptrInt)(int, int) = (size_t (Print::*)(int, int)) &Print::println;
unsigned long prlnInt = getMemberAddress(ptrInt);
// Print the raw hex addresses in memory
Serial.print("millis address: 0x"); Serial.println(millisAddr, HEX);
Serial.print("println(str) address: 0x"); Serial.println(prlnConstCharPtr, HEX);
Serial.print("println(int) address: 0x"); Serial.println(prlnInt, HEX);
}
void loop() {}
Při použití kódu buďte obezřetní. (Be carefull with using this code.)
Summary of Pitfalls
Overload resolution: You cannot just type &Serial.println. You must cast it explicitly to &Print::println along with its exact arguments to let the compiler know which type variation you want.
Hidden arguments:Serial.println(123) is actually mapped to println(int, int). If you try to target println(int), compilation will fail because that specific signature does not exist in Print.h.
My notes
I do not use definings template <... T> in my code and I understand it only barely, but the AI solution looks right to me. Anyway it is here only to demonstrate, how not close are millis() and Serial.println("hello") or Serial.println(123). The explanation of the differencies AI got right.
I left the question as I wrote it. My translation is this:
How in C++ (for AVR, amega328p, in Arduino) I get addressfor overload function Serial.println("hello") and for Serial.println(123), something like roughly
unsigned long millisAddr = millis; // call millis()
unsigned long prlnConstCharPtr = Serial.println???; // Serial.println("hello")
unsigned long prlnInt = Serial.println???; // Serial.println(123)
As @sterretje and @van_der_decken mentioned, you should have set all warnings reported and try to eliminate each and everyone of them in your code.
In Core are also some warnings, but the code works there somehow anyway and it is too complicate to fix even for advanced programmers and may introduce other problems.
I also have always set all warnings to Always.
It proved to me, that fixing all warnings is way faster, then fixing problem introduced by hiding warnings.
And in this case it would helped too, as the compiler would complain about this typo (missing parentheses or round brackets) as about type warning.
(And as we discussed here, this wrong type is easy to do with millis or other simply functions, but way harder to do with Serial.println or other more complicated functions.)
In addition to many overloaded member functions (in classes and on objects, aka methods), there are a few overloaded free functions. This fails
void setup() {
Serial.begin(115200);
long x = random;
Serial.println(x);
}
void loop() {}
with a similar error: "cannot resolve overloaded function 'random' based on conversion to type 'long int'". The random function takes either one or two arguments
random(max)
random(min, max)
Reading the second half of that error message, the compiler needs more details to "base on". For example, "a function that takes one big number and returns another"
long (*x)(long); // global so it can be used in both setup and loop
void setup() {
Serial.begin(115200);
x = random; // compiler figures out which one you want
}
void loop() {
Serial.println(x(millis()));
delay(1500);
}
This prints random numbers in an increasing range. Perfectly valid, no warnings. The declaration is the give-away -- once you understand how to read such things, and that they're possible.
And there may be also overloaded operators (like + - * / and others).
For example there are overloaded operators = and += for assigning String and < <= == != >= > for comparation
Al so if you define vectors, matrices and other more dimensional things, you may also define their adding, multipling and different operations to look naturally, regardless you multiply matrice by another matrice, vector, integer or float.
And new one more creative may be created too, like equalsIgnoreCasestartsWithendsWith and many others ...
Your problem is, that you look at a class method as the same as a simple function. But despite the fact that they are often both simply called 'function' they are very different for the compiler. So you cannot expect the same result if you replace a function name (e.g. 'millis') by a method name (here: 'myServo.write') .
What I have learned is that when a method is attached with an object by the dot (.) operator, a function is formed. For example: myServo.write(23);
==> write is the method
==> myServo is the object
==> myServo.write() is the function
It looks like a function. But it is handled differently than a simple function by the compiler. You must not treat that as the same. One main difference is a hidden parameter that is added by the compiler when calling it. That has nothing to do with overloading.
E.g. you can create a function pointer to a simple function, e.g. 'millis'. But you cannot create a function pointer to 'myServo.write'.
Also, millis is the identifier in the case of millis() function; but, myServo.write is not an identfier for myServo.write() function as it contains a dot (.).
class MyClass {
public:
void hello(int x) {
Serial.println(x);
}
};
void setup() {
Serial.begin(115200);
while (!Serial);
// 1. Define and obtain the pointer to member function
// using the scope resolution operator `::` and `&`.
void (MyClass::*funcPtr)(int) = &MyClass::hello;
// 2. Create an instance
MyClass obj;
// 3. Call in combination with an instance
(obj.*funcPtr)(10); // via an object
MyClass* pObj = &obj;
(pObj->*funcPtr)(20); // via a pointer
}
void loop() {}
You should first learn C++. From some official source, which describe detaily and correctly, what happens there. Even the compiler say, that you have there error and that you cannot convert types this way, as they are incompatible.
When you want to do such manipulations, you should know, what you are doing and what you are supposed to do so it would be the right way.
You not only just look, but ypu also say: "I do not know, what I am doing and what standard say and I do not care, for me all it looks alike, even when it is something different, so I insist to doi it wrong way and I request compiler to follow my bad formed ideas instead of following standards"
Sadly for you the compiler will follow standart anyway.