Remi Colinet
Remi Colinet

Reputation: 45

How to convert a float into an unsigned int in C++?

I want to convert a float to an unsigned int. When I use this code, the terminal print 3 :

#include <iostream>

int main() {
  float test = 3.4;
  std::cout << "test : " << int(test) << "\n";
}

But when I use this code I have an error :

#include <iostream>

int main() {
  float test = 3.4;
  std::cout << "test : " << unsigned int(test) << "\n";
}

My error is :

example.cc: In function ‘int main()’:
example.cc:5:29: error: expected primary-expression before ‘unsigned’
    5 |   std::cout << "test : " << unsigned int(test) << "\n";
      |    

Can someone help me ? I need to use an unsigned int. Thanks !

Upvotes: 1

Views: 464

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96906

The functional cast (type(expr), that is) requires the type to be spelled as a single word (without spaces, [], *, &, etc).

unsigned int is not a single word, so it's not allowed.

Your options are:

  • Using the regular C-style cast: (unsigned int)test.

  • Omitting the int. unsigned alone means the same thing as unsigned int, so you can write unsigned(test).

  • Using a static_cast: static_cast<unsigned int>(test).

Upvotes: 4

Related Questions