Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does char* (int) mean in C++?

Tags:

c++

pointers

I have the following line of code in one of the projects I am working on:

char* i2txt(int);

And I don't exactly understand what it does? With my half-knowledge I was trying to make it work with floats, so I changed the int to a float, but that gives me an error.

char* i2txt(int);
/*vs*/
char* i2txt(float);

Error Message :

Error LNK2019 unresolved external symbol "char * __cdecl i2txt(float)" (?i2txt@@YAPADM@Z) referenced in function "public: char * __thiscall DapChannel::getDurationTxt(void)" (?getDurationTxt@DapChannel@@QAEPADXZ)  PhotoZ  DapChannel.obj  1   
like image 616
Sarwagya Avatar asked Dec 13 '22 11:12

Sarwagya


1 Answers

The statement char* i2txt(int); is forward-declaring a function i2txt that takes an int as input, and returns a char*.

What is forward-declaration?

If you have a function used before it's declared, that results in an error:

#include <iostream>

int main() {
    foo(); // Error: foo not defined
} 
void foo() {
    std::cout << "Hello, world!"; 
}

Forward-declaration basically states "This function isn't defined yet, but I promise I'll define it eventually. In the above case, it'd look like this:

#include <iostream>

void foo(); // Forward declaration

int main() {
    foo(); // Now we can use it
}

void foo() {
    std::cout << "Hello, world!";
}

Why do you get an error when you change it to i2txt(float);?

This results in an error because suddenly, there's no i2txt(int) function to call. Because ints can be implicitly converted to float, the compiler still allows other functions to call i2txt(float), but no definition for i2txt(float) is ever provided, so there's a linker error:

#include <iostream>
char* i2txt(float);

int main() {
    std::cout << i2txt(10); // Tries calling i2txt(float)
}

// This provides a definition for i2txt(int), but the linker is still missing a definition for i2txt(float)
char* i2txt(int) {
    // ... stuff
}
like image 173
Alecto Irene Perez Avatar answered Dec 28 '22 23:12

Alecto Irene Perez