Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type of the errno variable in C++?

Tags:

c++

errno

I was doing some system programming in C++, and I want to pass the errno variable in linux systems to my exception handler. You can see example code in here https://pastebin.com/ppgMc8Hj

#include <sys/stat.h>
#include <cerrno>
#include <iostream>
#include <cstring>

std::string errorString(int errno){
    return std::strerror(errno);
}

int main(){
    struct stat sb;
    errno = 0;
    if(stat("/jdfj/", &sb)){
        errorString(errno);
    }
    else{
        std::cout << std::boolalpha << S_ISDIR(sb.st_mode) << std::endl;
    }
}

But it returns an error like this

In function 'int main()': 
 14:26: error: invalid conversion from 'int' to 'int* (*)()' [-fpermissive] 
  6:13: note: initializing argument 1 of 'std::string errorString(int* (*)())'.

I have seen here http://en.cppreference.com/w/cpp/string/byte/strerror that the standard function that returns a string from errno accepts an int as argument. My question is

  1. If it is an int type why doesn't it work in the above code?
  2. If not what is it's type?
like image 215
user123456 Avatar asked Oct 27 '25 20:10

user123456


1 Answers

errno is an implementation defined macro that expands to an expression of type int.

The problem is you are using the name errno as your function argument, which is not allowed. Since the name errno is a macro, it's expanded. For me, it results in std::string errorString(int (*_errno())). Your snippet works fine if you change the argument name.

std::string errorString(int error_num){
    return std::strerror(error_num);
}
like image 153
François Andrieux Avatar answered Oct 30 '25 12:10

François Andrieux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!